c - 如何允许在执行过程中读取空格?

标签 c string string-comparison

该程序是比较字符串,但是当我执行它时,间距出现问题。当我输入带空格的第一个字符串时,程序只是跳转到比较字符串,不允许我输入第二个字符串,如下所示:

>>"Enter first string":
"Hello Hey"
">>Enter second string:"
">>First string is more than the second string."

screenshot

这是我的代码:

#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/

相关文章:

python - 如何概括这个正则表达式,以便它开始捕获字符串开头的子字符串或者后面跟着其他单词的子字符串?

string - Ada 字符串比较

c# - C#中的双字节字符串比较

c - ocilib 的稳定性如何

c - 写入关闭的套接字没有按预期引发 SIGPIPE

c - 在 C 中反转 2 个字符串

sql - 分割字符串并返回mssql中最大的

c - #ifdef in c for filename 用于保护头文件中的静态函数

c - Berkeley DB 存储速度太慢

javascript - 如何将 '(1,2,3,4)' 更改为 '1,2,3,4'