How to read from input until newline is found using scanf()?
当我应该从输入中读取内容,直到有空格,然后直到用户按下Enter时,要求我使用C进行工作。
如果我这样做:
1 |
它将遵循第一条规则,但不会遵循第二条规则。
如果我写:
1 | I am smart |
我得到的等效于:
a =" I";
b =" am";
但是应该是:
a =" I";
b ="我很聪明";
我已经尝试过:
1 2 3 |
和
1 |
在第一个中,它等待用户按Ctrl + D(发送EOF),这不是我想要的。
在第二版中,它不会编译。 根据编译器:
warning: no closing ‘]’ for ‘%[’ format
有什么好办法解决这个问题吗?
这意味着结尾的
'
为了解决这个问题,您通常需要执行以下操作:
1 2 3 4 5 6 7 8 9 | 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. |
1 2 |
使用getchar和一段时间看起来像这样
1 2 3 4 5 6 7 8 | while(x = getchar()) { if(x == ' '||x == '\0') do what you need when space or return is detected else mystring.append(x) } |
抱歉,如果我编写了伪代码,但是一段时间以来我不使用C语言。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <stdio.h> #include <conio.h> #include <stdlib.h> int main(void) { int i = 0; char *a = (char *) malloc(sizeof(char) * 1024); while (1) { scanf("%c", &a[i]); if (a[i] == ' ') { break; } else { i++; } } a[i] = '\0'; i = 0; printf(" "); while (a[i] != '\0') { printf("%c", a[i]); i++; } free(a); getch(); return 0; } |
我为时已晚,但是您也可以尝试这种方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
听起来像是一个作业问题。 scanf()是用于此问题的错误函数。我建议getchar()或getch()。
注意:我故意不解决问题,因为这看起来像是作业,而只是指向正确的方向。
1 2 3 4 5 6 7 8 |
只需写s代替 n :)