I have added code tags and got rid of the red writing from your post, and you can see how much better it looks.
I tried your code, and had to get rid of the conio include and the getch call, but they didn’t seem to be essential.
What does the ^\n bit mean? Is that some sort of regular expression? When I deleted that, so I had scanf("%s", name[i]); the whole thing seemed to work.
Joined: Apr 07, 2012
Hi Thanks . I knew what you did in reply. My question was: (scanf("%[^\n]s",name[i]);) this code is used for taking input all characters of keyboard except return key. When it find return key at console , it stores all the characters including space in a character array of predefined size. I want to take loop and write this code inside that . As I want, it should take line of text as encounter return key and store in a new character array in each loop. But it does work only at once . Loop works well and iterate as according to the given condition but reads this line in the first turn of iteration and in second or next turn it escapes this line. Would you clear me why?
Joined: Oct 13, 2005
Don’t know. Sorry. I didn’t know you could use regular expressions in scanf like that.
Joined: Oct 13, 2005
I found a few links via Google; this one says it’s not a regex (obviously it only looks like a regex), but they are using sscanf.
[Methinks this belongs to the forum devoted to C and C++. I do not see posts made here all to often.]
Some suggestions to the OP:
Avoid doing I/O in C. If you are learning the language, you could simply hard-code your inputs. If you are in a professional environment, you will very likely be using a good library for I/O.
Avoid using scanf. If you have to read input in C, use getchar instead.
Absolutely do NOT give a finite sized stack allocated array to be assigned a value from scanf. Lookup BUFFER OVERFLOW on Google. Think of what could happen if the user were to provide a line as input that is longer than 49 characters in length. (Yes, you could specify in your format string to scanf, a length of your input -- but before you respond like so, see above point.)
Get into habit of examining a function's return value. In your particular example, scanf's return value would have provided you with very valuable information.
To answer your question --
The scanf's format specifier says "Keep reading all input until you encounter a newline, and store the result in the ith element of name." When scanf reads the input, it encounters the newline the first time. It leaves this newline in the input stream. As a result the newline is not consumed, and hence it is encountered in the second and the third time of your loop. The other lines of input is simply waiting to be read.
hope this helps,
"Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." -- Antoine de Saint-Exupery