使用 scanf() 从键盘读取时从先前的输入读取换行符 [英] Reading newline from previous input when reading from keyboard with scanf()

查看:11
本文介绍了使用 scanf() 从键盘读取时从先前的输入读取换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这本来应该很简单,但我无法从键盘读取连续输入.

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

代码如下:

#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;
}

发生了什么

当我输入一个字符串(例如:计算机)时,程序会读取换行符(' ')并将其放入character.下面是显示的样子:

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?

推荐答案

首先 scanf 读取输入的字符串并将 留在输入缓冲区中.下一次调用 scanf 读取该 并将其存储到 character.
试试这个

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. 

程序对超过一个字符的字符串不起作用,因为 scanf 一旦找到一个空白字符就会停止读取.您可以改用 fgets

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);

这篇关于使用 scanf() 从键盘读取时从先前的输入读取换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆