-
reading characters
Hi,
I am having some problems with my code. I am trying to read characters from scanf. What happens is that it doesnot read the whole character it read only 1 character. I tried making a loop but it keeps giving me errors.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c;
float i;
int number;
float f =50;
scanf("%c", &c);
number = atoi(c);
i=f+(float)number;
printf("%f",i );
return 0;
}
-
atoi takes a string, not a single character, and scanf with %c only reads a single character
You need something like
Code:
char c[10];
fgets( c, sizeof c, stdin );
number = atoi(c);
-
the thing is that we are only allowed to use scanf and we have to use characters.
-
Code:
char c[10];
scanf("%s", c);
If your teacher isn't letting you use strings, then this is just a bad assignment.
-
It's easier to scanf an int to begin with:
Code:
#include <stdio.h>
int main(void)
{
int number;
printf("Please give an integer and press enter: ");
/* read a number from the keyboard and assign it to 'number' */
scanf("%d", &number);
printf("You gave %d\n", number);
}
-
I think the idea of the program was to convert from a character to an integer to a float.
-
I am able to do it with strings. but the problem is that the teacher wants us to read character and then we have to convert all those character to floats so I can do some computations.
-
Code:
char string[9] = { 0 };
float f;
scanf("%c%c%c%c%c%c%c%c", string[0], string[1], string[2], string[3], string[4], string[5], string[6], string[7]);
sscanf(string, "%f", &f);
hehehehe
-
-
thanks guys I used fgets since the way my prof is saying it doesnot make sense.Thanks alot.