直到换行使用scanf函数发现如何从输入读​​取()? [英] How to read from input until newline is found using scanf()?

查看:174
本文介绍了直到换行使用scanf函数发现如何从输入读​​取()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求做在C工作的时候,我应该从输入读取,直到有一个空格,然后直到用户presses进入。
如果我这样做:

I was asked to do a work in C when I'm supposed to read from input until there's a space and then until the user presses enter. If I do this:

scanf("%2000s %2000s", a, b);

它会按照第1章,但不是第二个。结果
如果我写:

It will follow the 1st rule but not the 2nd.
If I write:

I am smart

我得到的是相当于:结果
A =I;结果
B =AM;结果
但它应该是:搜索
A =I;结果
B =很聪明,结果

What I get is equivalent to:
a = "I";
b = "am";
But It should be:
a = "I";
b = "am smart";

我已经尝试过:

scanf("%2000s %2000[^\n]\n", a, b);

scanf("%2000s %2000[^\0]\0", a, b);

在第一的,它等待用户preSS <大骨节病>控制 + <大骨节病> D (发送EOF)这不是我想要的。
在第二之一,它不会编译。根据编译器:

In the 1st one, it waits for the user to press Ctrl+D (to send EOF) and that's not what I want. In the 2nd one, it won't compile. According to the compiler:

警告:'%['格式没有结束]

warning: no closing ‘]’ for ‘%[’ format

要解决这个什么好的办法?

Any good way to solve this?

推荐答案

scanf函数(和表兄弟)有一个稍显陌生的特点:任何空白格式字符串空间(外一扫描集的)匹配的输入空格的任意量。碰巧的是,至少在默认的C区域,一个新的行被划分为空白。

scanf (and cousins) have one slightly strange characteristic: any white space in the format string (outside of a scanset) matches an arbitrary amount of white space in the input. As it happens, at least in the default "C" locale, a new-line is classified as white space.

这意味着尾随的'\\ n'尝试匹配不​​仅的的新线,但任何成功的空白,以及。它不会被认为是匹配的,直到信号输入的结束,否则进入一些非空白字符。

This means the trailing '\n' is trying to match not only a new-line, but any succeeding white-space as well. It won't be considered matched until you signal the end of the input, or else enter some non-white space character.

要解决这个问题,你通常希望做这样的事情:

To deal with this, you typically want to do something like this:

scanf("%2000s %2000[^\n]%c", a, b, c);

if (c=='\n')
    // we read the whole line
else
    // the rest of the line was more than 2000 characters long. `c` contains a 
    // character from the input, and there's potentially more after that as well.

这篇关于直到换行使用scanf函数发现如何从输入读​​取()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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