scanning in character string

This is a discussion on scanning in character string within the C Programming forums, part of the General Programming Boards category; I have a question in regards to scanning in a character array with spaces for a project im working on ...

scanning in character string

I have a question in regards to scanning in a character array with spaces for a project im working on for an introductory class in C programming.

I know that I cant use the scanf function becasue it will stop scanning in the characters once it sees a space. Our teacher told us to use the "gets" function.

The string can have a maxium length of 50 characters. So I defined the string variable as
char str[51];
to leave an extra space for the the \0

I can get the gets function to work in an easy case

Code:

char str[51];
printf("Enter the string:");
gets(str);

it works fine for this. This is probally a dumb question, but will the gets function be skipped, if it is inside a loop. My program just seems to skip right over the gets function, but if I replace it with a scanf function everything works fine(except for the fact that I cant scan in more than one word).

Here is the basic structure of the part of the program that I am having trouble with.

http://faq.cprogramming.com/cgi-bin/...&id=1043284351
Also, the reason that gets is being skipped is because it is picking up the newline character left on the screen by scanf(), Don't use gets, but if you use scanf(), keep in mind that it leaves the enter on the buffer, waiting for some input function to grab it.

So stdin is referring to the input buffer. I am not reading the string from a file, but rather the user types it in.

will I have to flush the buffer after the user goes through the "scanf" for a single integer input, but before going through the "fgets". I know that fflush(stdin) is bad from various members of the board, as well as the faq, but for some reason, that is what our teacher tells us to do. I was having a problem before with the "gets" function being skipped becasue it would read in a newline from the "scanf" function. If I somehow cleared the buffer after my "scanf" statement, and used "fgets" instead of "gets", would my problem be solved?

thanks for the help,
Zack

Originally Posted by Salem

Code:

FILE *fp = fopen( "file.txt", "r" );
fgets( buff, sizeof buff, fp );

stdin is just the predefined variable of type FILE* which is attached to the standard input stream of your program.

Similarly,

Code:

scanf( "%d", &myint );
fscanf( stdin, "%d", &myint );

are the same thing.

To avoid all the problems which scanf has with leaving newlines (and generally poor error recovery in general), just use fgets() to read a line, then use sscanf() to parse the line.