Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

c - Reading newline from previous input when reading from keyboard with scanf()

This was supposed to be very simple, but I'm having trouble to read successive inputs from the keyboard.

Here's the code:

#include <string.h>
#include <stdio.h>

int main()
{
    char string[200];
    char character;
    printf ("write something: ");
    scanf ("%s", string);
    printf ("%s", string);
    printf ("
write a character: ");
    scanf ("%c", &character);
    printf ("
Character %c  Correspondent number: %d
", character, character);

    return 0;
}

What is happening

When I enter a string (e.g.: computer), the program reads the newline (' ') and puts it in character. Here is how the display looks like:

 write something: computer
 computer
 Character:
    Correspondent number: 10

Moreover, the program does not work for strings with more than one word. How could I overcome these problems?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First scanf read the entered string and left behind in the input buffer. Next call to scanf read that and store it to character.
Try this

scanf (" %c", &characte);   
     // ^A space before %c in scanf can skip any number of white space characters. 

Program will not work for strings more than one character because scanf stops reading once find a white space character. You can use fgets instead

 fgets(string, 200, stdin);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...