如何使用scanf()从输入中读取直到找到换行符? [英] How to read from input until newline is found using scanf()?

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

问题描述

当我应该从输入中读取直到有一个空格然后直到用户按下回车键时,我被要求在 C 中做一项工作.如果我这样做:

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

它将遵循第一条规则,而不是第二条.
如果我写:

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

I am smart

我得到的相当于:
a = "我";
b = "我";
但应该是:
a = "我";
b = "我很聪明";

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

我已经试过了:

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

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

在第一个中,它等待用户按 Ctrl+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

有什么好办法解决吗?

推荐答案

scanf(和表兄弟)有一个稍微奇怪的特征:格式字符串中的空白(最多放置)匹配任意数量输入中的空白.碰巧的是,至少在默认的C"中.语言环境,换行符被归类为空白.

scanf (and cousins) have one slightly strange characteristic: white space in (most placed in) the format string 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.

这意味着尾随的 ' ' 不仅试图匹配 a 换行符,而且还试图匹配任何后续的空格.在您发出输入结束信号或输入一些非空白字符之前,它不会被视为匹配.

This means the trailing ' ' 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.

一种处理方法是这样的:

One way to deal with that is something like this:

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

if (c=='
')
    // 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 的返回值,它会告诉您成功的转换次数.在这种情况下,您将寻找 3 来指示所有转换都成功.

Depending on the situation, you might also want to check the return value from scanf, which tells you the number of conversions that were successful. In this case, you'd be looking for 3 to indicate that all the conversions were successful.

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

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