英文:
C program won't use printf after scanf
问题
我是新手C语言编程,正在编写一个非常简单的C程序,它只接受输入然后将其回显。代码显示了第一个printf,其中是一个$符号,并允许您输入内容,但不会将文本回显给您。以下是代码:
```C
char input[50];
printf("$");
scanf("%s\n", input);
printf("\n %s", input);
我以为可能是编译问题,但没有任何变化。我使用了make token,这是文件的名称。
<details>
<summary>英文:</summary>
I am new to C and am writing a very simple C program which just provides a input and repeats it back to you. The code shows the first print f which is a $ and lets you input something but will not print the text back to you. Here is the code:
char input[50];
printf("$");
scanf("%s\n", input);
printf("\n %s", input);
I thought it might have been a compile issue but nothing changes. I use make token which is the name of the file.
</details>
# 答案1
**得分**: 4
移除 `scanf()` 格式字符串中的 `"\n"`。末尾的 `"\n"` 指示 `scanf()` 匹配任意数量的空白字符,并且只有在遇到非空白字符时才知道何时完成。与此同时,您期望它在读取第一个 `"\n"` 后返回。考虑使用 `fgets()` 代替。
```c
#include <stdio.h>
int main() {
char input[50];
printf("$");
scanf("%s", input);
printf("\n %s", input);
}
以及示例会话:
$abc
abc
英文:
Remove the "\n" in the scanf()
format string. The trailing "\n" instructs scanf()
to match any number of white space characters and it will only know when it's done when encountering a non-white space character. Meanwhile you expect it to return after reading the first "\n". Consider using fgets()
instead.
#include <stdio.h>
int main() {
char input[50];
printf("$");
scanf("%s", input);
printf("\n %s", input);
}
and example session:
$abc
abc
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论