该程序是比较字符串,但是当我执行它时,间距出现问题。当我输入带空格的第一个字符串时,程序只是跳转到比较字符串,不允许我输入第二个字符串,如下所示:
>>"Enter first string":
"Hello Hey"
">>Enter second string:"
">>First string is more than the second string."
这是我的代码:
#include<stdio.h>
#include<string.h>
int main (void) {
int result; //store results
char input1[50];
char input2[50];
printf("Enter first string:\n");
scanf("%[^\n]s",input1);
printf("Enter second string:\n");
scanf("%[^\n]s",input2);
result = strcmp(input1, input2);
if (result==0)
printf("First string is equal to second string\n");
if (result>0)
printf("First string is greater than second string\n");
if (result<0)
printf("First string is less than the second string\n");
return 0;
}
最佳答案
添加空格:
scanf(" %[^\n]s",input1);
scanf(" %[^\n]s",input2);
它将消耗之前输入中遇到的所有空格。
当您输入任何内容时,您还可以在输入内容中输入一个换行符(空格)。代码中的第二个 scanf
正在读取该换行符。
问题:
How do I allow spaces to be read during execution? (the question)
您已经在 scanf("%[^\n]s",input1);
中使用 [^\n]
执行此操作,这意味着读取输入直到遇到新行 (\n
)。另外,并不是说 \n
本身不能以这种方式读取。
输出:
Enter first string:
Strings in C
Enter second string:
Strings in C
First string is equal to second string
关于c - 如何允许在执行过程中读取空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37898565/