【问题标题】:C string compare wont allow space barC字符串比较不允许空格键
【发布时间】:2017-02-13 16:10:29
【问题描述】:

使用 cprogrammingsimplified 教程编写我自己的字符串比较。 完成重新格式化并运行它。 适用于单个单词,

但是

键入空格键会跳过第二次扫描并立即输出 '字不一样'

有人知道如何允许使用单个空格键吗?

提前致谢。

#include <stdio.h>

int mystrcmp(char s1[], char s2[]);

int main(){
    char s1[10], s2[10];
    int flag;

    printf("Type a string of 10\n\n");
    scanf("%s",&s1);
    printf("type another string of 10 to compare\n\n");
    scanf("%s",&s2);

    flag = mystrcmp(s1,s2);

    if(flag==0)
        printf("the words are the same\n\n");

    else
        printf("the words are not the same\n\n");

    return 0;
}

int mystrcmp(char s1[], char s2[]){
    int l=0;

    while (s1[l] == s2[l]) {
        if (s1[l] == '\0' || s2[l] == '\0')
            break;
        l++;
    }

    if (s1[l] == '\0' && s2[l] == '\0')
        return 0;
    else
        return -1;
}

【问题讨论】:

  • 请给出两个似乎不起作用的示例输入
  • 空格是scanf函数的分隔符。所以只有第一个单词会放在 s1 中。
  • 非常感谢大家,只是在其他任务中,所以必须在这里返回所有额外的信息!

标签: c string-comparison


【解决方案1】:

使用fgets() 读取整行,而不是scanf() 读取空格分隔的单词。

请记住,fgets() 将在字符串中包含换行符。

【讨论】:

    【解决方案2】:

    不是strcmp 不允许空格键,而是scanf%s 格式说明符。输入在空格处被截断,因此您读取的第二个字符串实际上是第一个字符串的延续。

    您可以通过在格式说明符中使用 %9[^\n] 而不是 %s 来解决此问题:

    printf("Type a string of 10\n\n");
    scanf("%9[^\n]",s1); //s1 is char [10]
    printf("type another string of 10 to compare\n\n");
    scanf("%9[^\n]",s2); //s2 is char [10]
    

    9 将输入限制为 9 个字符,因为您使用的是 10 个字符的缓冲区。

    【讨论】:

      【解决方案3】:

      许多答案告诉你scanf("%s",s1) 只逐字阅读。这是因为默认情况下scanf("%s",s1) 由所有空格分隔,这包括\t\n&lt;space&gt; 或任何其他您能想到的。

      scanf("%[^\n]s",s1) 所做的是将分隔符设置为\n。所以实际上读取所有其他空格。

      @dasablinklight 还在 '[^\n]' 之前指定了一个 9,这表示 scanf() 从输入缓冲区中获取 9 个值。

      IMO scanf() 是一个非常好的功能,因为它具有隐藏 功能。我建议您在documentation 中阅读更多相关信息。

      【讨论】:

        【解决方案4】:

        问题是如果你在第一行输入abc def,第一个scanf("%s", s1)(不需要和号——应该不存在)读取abc,第二个读取def。而那些并不相等。输入very very,你会发现单词是相等的。 %s 在空格处停止阅读。

        大小为 10 的缓冲区太小,不舒适。

        修复:使用fgets() 或POSIX 的getline() 读取行(例如char s1[1024], s2[1024];),删除尾随换行符(可能:s1[strcspn(s1, "\n")] = '\0'; 是一种可靠的方法),然后继续比较行。

        【讨论】:

          猜你喜欢
          • 2012-11-15
          • 1970-01-01
          • 1970-01-01
          • 2014-10-02
          • 1970-01-01
          • 2018-01-16
          • 1970-01-01
          • 2012-10-18
          • 2015-10-04
          相关资源
          最近更新 更多