Up vote 0 down vote favorite share g+ share fb share tw.
I, for the life of me, cannot be at peace with c strings and input/output. For my program I simply enter a string and it gets processed in the following code: (tmpstring and ch are already defined) For my incomning input, I write in terminal: echo "test" | . /program int main(int argc, char *argv) { char tmpstring2048; int ch; int r; int c; fgets(tmpstring, sizeof tmpstring, stdin); while((ch = fgetc(stdin))!
= EOF && ch! = '\n'); tmpstringstrlen(tmpstring)-1='\0'; strncpy(opponent, tmpstring+1, strlen(tmpstring+1)); move(); Inside of move(); char buffer2048={0}; int r, c; r=0; c=0; printf("Your move (row column):"); if((fgets(buffer, sizeof buffer, stdin)==NULL) || ((sscanf(buffer,"%d %d", &r, &c))! =2)){ printf("Invalid input.
Please insert two numbers separated by whitespace. \n"); exit(1); } //continues Executing this goes straight into the invalid input without asking for more input. I've read all around about how you shouldn't clear stdin (and that it's impossible) but I really don't know what to do.
I clearly tried to "dump" stdin with the second part of the while loop. I've changed the && after the first condition to an || in the while loop. No change.
Overall, how can I ask for more input after already used fgets? *edit: more code and separated the original while loop c stdin fgets sscanf link|improve this question edited Mar 10 '11 at 22:41 asked Mar 10 '11 at 22:13boses11.
Suggestion: separate stuff into different statements. In your code above you have fgets and fgetc in the same statement (also fgets and sscanf later). – pmg Mar 10 '11 at 22:21 I'm having trouble reproducing your problem.
I simply call fgets(tmpstr, sizeof(tmpstr), stdin); fgets(buffer, sizeof(buffer), stdin); sscanf(buffer, "%d %d", &a, &b); without any loops and it works. Could you maybe show more of your code? – dialer Mar 10 '11 at 22:30 1 With echo "test" | .
/program the stream stdin gets into end-of-file condition right after the first fgets. The while loop terminates because ch is assigned EOF and in the move() function fgets() returns NULL because stdin is in end-of-file condition. – pmg Mar 10 '11 at 22:57 OP: after removing the while loop and instead of adding input via piping but rather asking for input in the beginning, it worked.
So then I must ask, you can never repeat fgets if the stdin doesn't have a '\n'? – boses Mar 10 '11 at 23:08 2 Your strncpy doesn't copy the terminating NUL. Never ever use strncpy.
– Jim Balter Mar 10 '117 at 0:02.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.