Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Read one character at a time with scanf

Status
Not open for further replies.

daisypolly

Programmer
Apr 28, 2005
38
0
0
CA
Hi,
How can I read 1 character with scanf and then store all the characters in the variable.for example I am trying to do this but it doesnot work;
Code:
#include <stdio.h>
#include <stdlib.h>

int main()
{
	char c;
	float i;
	int number;
	float f =50;
	char newchar;
while(c!='\n')
   					 {
   				    /* perform task */

   				      scanf("%c",&c);
   				      newchar=c;
   number = atoi(newchar);
					 }   ;


	i=f+(float)number;

	printf("%f",i  );

	return 0;


}
 
Hi:

The problem with your code is that you are only converting the last character entered. If you are going to use scanf in this manner, I'd convert a string - not just 1 character:

Code:
include <stdio.h>
#include <stdlib.h>

int main()
{
    char c;
    float i;
    int number;
    float f =50;
    char newchar;
    char newstr[50];

    scanf("%s",&newstr);

    number = atoi(newstr);
    printf("%d\n", number);
}
 
If you're reading one char at a time why on earth are you using scanf? man getc and see how much easier your code gets!

Columb Healy
 
Also
Code:
while(c!='\n')
You don't initialize c to any value, so when it gets here it might be '\n' already and the loop would never execute.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top