C程序在使用scanf后不会使用printf。

huangapple go评论63阅读模式
英文:

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 &lt;stdio.h&gt;

int main() {
	char input[50];
	printf(&quot;$&quot;);
	scanf(&quot;%s&quot;, input);
	printf(&quot;\n %s&quot;, input);
}

and example session:

$abc

 abc

huangapple
  • 本文由 发表于 2023年2月18日 10:52:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定