Using this code
void echo_char_code() {
int x;
printf ("Please enter a character:\n");
x = getchar();
printf("The character code of '%c' is %d", putchar(x), putchar(x));
printf(". \n");
}
int main() {
echo_char_code();
return 0;
}
but for some reason my output is
AAThe character code of 'A' is 65.
and I'm wondering why the "AA" is appearing at the start and not just as the 'A' & 65 that I want it too.
You shouldn't pass putchar(x) as argument, instead use the variable x.
void echo_char_code() {
int x;
printf ("Please enter a character:\n");
x = getchar ();
printf("The character code of '%c' is %d", x, x)); // changing putchar(x) to x solves the problem.
printf (". \n");
}
int main() {
echo_char_code();
return 0;
}
In this line
printf("The character code of '%c' is %d",putchar(x),putchar(x));
you are calling putchar() twice, which outputs x twice.
You are also using the return values of those two calls to do a formatted output.
The return value of putchar() happens to be (in case of success) the written char, which makes it somewhat transparent.
The order of this is probably not predictable, but it does explain your observed result.
Compare https://en.cppreference.com/w/c/io/putchar
it states
Return value
On success, returns the written character.
Related
When I enter 2, I wish to get this output:
value: 2.4
But when I do the multiplication, I am getting this:
value: 2.400000
This is my code:
#include <stdio.h>
int main()
{
float num;
float result;
printf("Number: ");
scanf("%f", &num);
result = num * 1.2;
printf("Result: %f", result);
}
What can I do?
You can specify how many digits you want to print after the decimal point by using %.Nf where N is the number of digits after the decimal point. In your use case, %.1f: printf("Result: %.1f", result).
There are some other issues in your code. You are making use of scanf(), but you are not checking its return value. This may cause your code to break.
scanf() returns the number of arguments it successfully parsed. If, for any reason, it fails, it doesn't alter the arguments you gave it, and it leaves the input buffer intact. This means whenever you try again and read from the input buffer, it will automatically fail since
it previously failed to parse it, and
it didn't clear it, so it's always there.
This will result in an infinite loop.
To solve the issue, you need to clear the input buffer in case scanf() fails. By clearing the buffer, I mean read and discard everything up until a newline (when you previously pressed Enter) is encountered.
void getfloat(const char *message, float *f)
{
while (true) {
printf("%s: ", message);
int rc = scanf("%f", f);
if (rc == 1 || rc == EOF) break; // Break if the user entered a "valid" float number, or EOF is encountered.
scanf("%*[^\n]"); // Read an discard everything up until a newline is found.
}
}
You can use it in your main like that:
int main(void) // Note the void here when a function doesn't take any arguments
{
float num;
float result;
getfloat("Number", &num);
result = num * 1.2;
printf("Result: %.1f", result); // Print only one digit after the decimal point.
}
Sample output:
Number: x
Number: x12.45
Number: 12.75
Result: 15.3
Hi I am studying C language by myself.
My question is, is there something I missed which need to know when working with scanf() that takes char value?
To practice do...while loop, I wrote some code like below but it did not work as I expected.
#include <stdio.h>
int main()
{
char y_or_n;
int x =1;
int y;
do
{
printf("ENTER A NUMBER\n");
scanf("%d", &y);
printf("THE NUMBER WILL BE ADDED TO x WHICH IS %d\n", x);
x = x+y;
printf("x TURNED INTO %d\n", x);
printf("KEEP DOING THIS?(y/n)\n");
scanf(" %s", &y_or_n);
printf("x is %d\n", x);
}
while(y_or_n =='y');
printf("GOOD BYE\n");
return 0;
}
For the first loop, it worked as I expected.
For example, when I entered 7, x turned into 8. But after scanf() was executed, value of x was changed into 0.
So from second loop, value of x changed temporarily into value of y and changed again into 0.
I guessed that there is something wrong with scanf() function and modified the code slightly: changed type of y_or_n into integer so that scanf() takes integer value.
The modified code is like below
include <stdio.h>
int main()
{
int y_or_n;
int x =1;
int y;
do
{
printf("ENTER A NUMBER\n");
scanf("%d", &y);
printf("THE NUMBER WILL BE ADDED TO x WHICH IS %d\n", x);
x = x+y;
printf("x TURNED INTO %d\n", x);
printf("KEEP DOING THIS?(y/n)\n");
scanf(" %d", &y_or_n);
printf("x is %d\n", x);
}
while(y_or_n ==1);
printf("GOOD BYE\n");
return 0;
}
This time the code worked as I expected.
Value of x was not changed into 0 even after an execution of scanf() and every time I entered a number that number was added to x.
If my question is not clear, please let me know.
Thank you for reading.
%s is for reading null-terminated strings, so passing pointer to one-byte buffer for that is bad.
It seems the variable x is placed just after the variable y_or_n on the memory and writing of terminating null-character by scanf() is setting value of x to 0.
To read one character, use %c instead.
char y_or_n;
/* ... */
scanf(" %c", &y_or_n);
I'm running this program in C to convert Fahrenheit to Celsius and need to accept only integer value from the user.
Please tell me how I can modify this?
int main() {
int x;
double y;
while(x>0) {
printf("Enter the temperature in Fahrenheit:");
scanf("%d", &x);
y=((x-32)/1.8)
printf("%f\n",y);
}
}
The reason your code does not work is that sometimes scanf does not read anything, so it does not modify x.
You know that scanf read something by checking its return value. It returns the number of "scanned" items. In this case, the number must be 1.
When scanf returns 0 instead, you should read and discard the data in the buffer. You do it by supplying %*[^\n] format specifier, which means "read and discard input up to '\n' character. The complete snippet that reads an int until success looks like this:
while (scanf("%d", &x) != 1) {
printf("Please enter a valid number:");
scanf("%*[^\n]");
}
Note: It goes without saying that you should fix your syntax error with the missing semicolon ; on the line that computes y.
You can use below code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
double y;
char str1[5];
int num1,i;
bool yes = true;
while(x>0)
{
printf("Enter the temperature in Fahrenheit:");
scanf("%s",str1);
for(i=0;str1[i]!='\0';i++)
if(!(str1[i]>=48&&str1[i]<=56))
{
printf("The value is invalid \n");
yes = false;
}
num1 = atoi(str1);
if(yes == true)
{
printf("This Number is %d\n",num1);
y=((num1-32)/1.8);
printf("%f\n",y);
}
}
}
I have a problem writing code which does the following: declare a struct{char c; int x; } array and load it with scanf via a loop. After it's loaded, a call to function f will be made which will replace every occurrence of digits in the struct's component c with 0, and will return the sum of the digits replaced by zero.
Code and output are below and I have problem that the loop in the function f seems to iterate one time, and it gives out some really weird values.
This is an exam question so I have to use printf, scanf etc. Also I have that exam in an hour so any quick help is appreciated :)
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 2
struct par {
char c;
int x;
};
int f(struct par *niz) {
int i;
int n=0;
for(i=0; i<MAX; i++) {
if(isdigit(niz[i].c)) {
niz[i].c = niz[i].c-'0';
printf("niz[i].c = %d\n i = %d", niz[i].c, i);
n=n+niz[i].c;
niz[i].c='0';
}
}
return n;
}
void main() {
int n;
int i;
struct par niz[MAX];
printf("enter\n");
for(i=0; i<MAX; i++) {
scanf("%c", &niz[i].c);
scanf("%d", &niz[i].x);
}
n=f(niz);
for(int i=0; i<MAX; i++) {
printf("%d\n", niz[i].c);
printf("%d\n", niz[i].x);
}
printf("n = %d\n", n);
}
OUTPUT:
enter
2
2
2
niz[i].c = 2
i = 048
2
10
2
n = 2
When you press enter after the first input, the newline is not scanned by scanf and is left in the input buffer. When you then try to read the number scanf sees the newline and not a number so doesn't scan anything.
The simple solution to that is to add a leading space in front of the formats:
scanf(" %c", &niz[i].c);
scanf(" %d", &niz[i].x);
/* ^ */
This tells scanf to skip whitespace.
Use
niz[i].c = getchar();
instead of
scanf("%c", &niz[i].c);
or, you can use other better methods for getting char input discussed at SO,
Now,
You see second time you provided input only once, that is because the Enter you pressed after giving 2 as input to first char remained in input buffer, and was read on second iteration.
You are getting 10 as output, because, it is ASCII for \r, the Enter. It is not a digit, so not replaced to be '0'.
I am looking at your code (i am not using console for a decade, but ) here are some insights:
try to rename MAX with something else
do not know your IDE but sometimes MAX is reserved
and using it as macro can cause problems on some compilers
change scanf("%c", &niz[i].c) to scanf("%c", &(niz[i].c))
just to be shore that correct adsress is send to scanf
change scanf("%d", &niz[i].x) to scanf("%i", &(niz[i].x))
change "%d" to the correct value (this is main your problem)
"%c" for char
"%i" for int
Try to trace line by line and watch for improper variables change if above points does not help
weird values?
because you forgot "\n" after the line, so next print is behind the line "i = %d".
And, check return value of every function except ones that return void.
#include <stdio.h>
int main (void)
{
int T, y, z;
scanf ("%i\n", &T);
for (T; T > 0 ; --T)
{
scanf ("%i\n", &y);
}
return 0;
}
If I input 4, shouldn't it take 4 more inputs? Instead it allows me to enter 5 integers! Tried it for other numbers too.
The format string in scanf works as follows (see http://www.cplusplus.com/reference/cstdio/scanf/)
[The format is a] C string that contains a sequence of characters that control how
characters extracted from the stream are treated:
Whitespace
character: the function will read and ignore any whitespace characters
encountered before the next non-whitespace character ...
In both your scanf() you have a newline. Therefore the first time you hit the enter key, it is ignored by scanf.
Some of the answers are telling you to modify the loop... this is incorrect, your loop is fine. it is the above that's causing you the headache. Try the following:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int T, y, z;
scanf ("%i", &T);
printf("Count is= %d\n", T);
for (T; T > 0 ; --T)
{
printf("T= %d\n", T);
scanf ("%i", &y);
}
return 0;
}
EDIT: Thank you to Daniel Fischer for his comment about flushing stdin, which I have now removed. Found this explanation (Using fflush(stdin)).
Just get rid of \n from your scanf