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

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

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

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

 我很聪明 

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

我已经尝试过:

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

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

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

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

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

scanf (和cousins)有一个稍微奇怪的特征:格式字符串中的任何空格(扫描集之外)与输入中的任意数量的空白区域相匹配。 碰巧,至少在默认的“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. 
 scanf("%2000s %2000[^\n]", a, b); 

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

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

很抱歉,如果我写了一段伪代码,但我暂时不使用C语言。

 #include  #include  #include  int main(void) { int i = 0; char *a = (char *) malloc(sizeof(char) * 1024); while (1) { scanf("%c", &a[i]); if (a[i] == '\n') { break; } else { i++; } } a[i] = '\0'; i = 0; printf("\n"); while (a[i] != '\0') { printf("%c", a[i]); i++; } free(a); getch(); return 0; } 

我来不及了,但你也可以尝试这种方法。

 #include  #include  int main() { int i=0, j=0, arr[100]; char temp; while(scanf("%d%c", &arr[i], &temp)){ i++; if(temp=='\n'){ break; } } for(j=0; j 

听起来像是一个家庭作业问题。 scanf()是用于解决问题的错误函数。 我推荐getchar()或getch()。

注意:我故意不解决问题,因为这看起来像是家庭作业,而只是指向正确的方向。

 #include  int main() { char a[5],b[10]; scanf("%2000s %2000[^\n]s",a,b); printf("a=%sb=%s",a,b); } 

只写s代替\ n 🙂