Advertisement

Newline Overtakes scanf

Started by September 21, 2002 07:44 PM
4 comments, last by Alpha_ProgDes 22 years, 1 month ago
sorry for the double post. i would move it if i knew how. anyway... scanf("%c", character); scanf("%d", number); for some reason if you enter the character then Enter the second scanf is skipped. but... scanf("%c", character); scanf(" %d", number); will not allow the second scanf to skip (notice the space between the quote and %d). why is that? i''ve looked for docs on this but couldn''t find any. and found out this trick last year, but couldn''t find the webpage i originally saw it on to see if the author had an answer for it.

Beginner in Game Development?  Read here. And read here.

 

The second scanf isn''t skipped, it reads the newline character (''\n'') generated when the user presses the enter key.
Advertisement
the above poster is correct what you need to do is to grab the ''\n'' character and get rid of it for your program to work right. Something along the lines of :

char string[256];
int i=0;
do
{
getch(string);
i++;
}while( string[i--] != ''\n'' && i < 256)
int count;scanf( "%c\n%n", &character, &count );if( count != 2 )    printf( "Missing newline after %c", character );scanf( "%d", &number );     


Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]


[edited by - Fruny on September 24, 2002 2:49:18 AM]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Or a slightly more compact way is

char c;
int i;

scanf("%c%*c", &c);
scanf("%d", &i);


The * asterisk in the second part of the first scanf statement simply takes and discards the character read.
I allways use getch() or getche() from .
Works fine with a while loop and a switch - case "menu".
f.ex

char ch;

while(ch!=27) // 27 = ASCII for ESC
{
ch = getch(); // getche() if you want to see the choice on screen
switch(ch)
{
case 49:
cout << "you pressed 1!\n";
break;
case 50:
cout << "you pressed 2!\n";
break;

/* Optional if you want to..
default:
cout << "Thats no valid key!\n";
*/
}

Offcourse, since you allready got an answer this might be a vaste of time.. but I like to post!


- Twixly, the animated fool.
- ICQ : 29553198
Windows - Dev-Cpp 4.9.9 - SDL - SDL_Net

This topic is closed to new replies.

Advertisement