如何从输入读取,直到使用scanf()找到换行符?

bru*_*ais 18 c format scanf

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

scanf("%2000s %2000s", a, b);
Run Code Online (Sandbox Code Playgroud)

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

I am smart

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

我已经尝试过:

scanf("%2000s %2000[^\n]\n", a, b);
Run Code Online (Sandbox Code Playgroud)

scanf("%2000s %2000[^\0]\0", a, b);
Run Code Online (Sandbox Code Playgroud)

在第一个,它等待用户按Ctrl+ D(发送EOF),这不是我想要的.在第二个,它不会编译.根据编译器:

警告:'%['格式没有关闭']'

有什么好办法解决这个问题吗?

Jer*_*fin 37

scanf(和表兄弟)有一个稍微奇怪的特征:格式字符串中的任何空格(扫描集之外)与输入中任意数量的空白区域相匹配.碰巧,至少在默认的"C"语言环境中,新行被归类为空白区域.

这意味着尾随'\n'尝试匹配不仅是一个新的行,但任何成功的白色空间也是如此.在您发出输入结束信号之前,它将不会被视为匹配,或者输入一些非空格字符.

要解决这个问题,您通常希望执行以下操作:

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.
Run Code Online (Sandbox Code Playgroud)


VHa*_*avy 8

scanf("%2000s %2000[^\n]", a, b);
Run Code Online (Sandbox Code Playgroud)


小智 5

使用 getchar 和一段时间,看起来像这样

while(x = getchar())
{   
    if(x == '\n'||x == '\0')
       do what you need when space or return is detected
    else
        mystring.append(x)
}
Run Code Online (Sandbox Code Playgroud)

对不起,如果我写了一个伪代码,但我有一段时间不使用 C 语言。