用scanf函数从键盘读取数据时从previous输入读取行() [英] Reading newline from previous input when reading from keyboard with scanf()

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

问题描述

这应该是很简单的,但我有麻烦,从键盘读取连续输入。

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

这里的code:

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

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

    return 0;
}

这是怎么回事

当我输入一个字符串(如:计算机),该程序读取行(的'\\ n'),并把它放在字符。这里是显示的样子:

When I enter a string (e.g.: computer), the program reads the newline ('\n') 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函数读取输入的字符串,并留下 \\ n 在输入缓冲器。到 scanf函数下一次调用读取 \\ n ,并将其存储到字符。结果
试试这个

First scanf read the entered string and left behind \n in the input buffer. Next call to scanf read that \n 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函数从键盘读取数据时从previous输入读取行()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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