【问题标题】:reading 2 strings on each line from the input and printing them in loop in C从输入中读取每行上的 2 个字符串并在 C 中循环打印它们
【发布时间】:2020-08-18 16:07:55
【问题描述】:

我正在尝试编写一个程序来读取输入(每行有 2 个单词)并且我想打印这些单词。但它给了我一个奇怪的输出。

#include <stdio.h>
int main() 
{
    char word1[21], word2[21], text[5005];
    int line = 0, i;
    while (fgets(text, sizeof(text), stdin))
    { 
        sscanf(text, "%s %s", &word1[line], &word2[line]);
        line++;
    }
    for(i = 0; i < line; i++)
       {
           printf("%s %s", word1, word2);
           printf("\n");
        }
    return 0;
}

当我输入例如:

dog cat
black white

输出是:

dblack cwhite
dblack cwhite

我该如何做这样的输出?

dog cat
black white

【问题讨论】:

    标签: c string io printf


    【解决方案1】:

    1.

    word1word2 只是 char 的数组:

    char word1[21], word2[21];
    

    因此:

    while (fgets(text, sizeof(text), stdin))
    { 
        sscanf(text, "%s %s", &word1[line], &word2[line]);
        line++;
    } 
    

    将不同行的输入字符串连续写入wordN中的下一个字符元素,而不是另一个word内存。

    这会导致

    dblack cwhite
    

    输出。

    blackword1 的第二个元素开始写入,其中dog 之前存储,从第一个元素开始。 whiteword2 的第二个元素开始写入,其中cat 之前存储,从第一个元素开始。除了第一个元素之外,两者都使用相同的内存。

    2.

    while (fgets(text, sizeof(text), stdin)) - 如果没有发生I/O 错误,条件将始终为真。


    如果您只想无休止地打印出每行输入的 2 个单词(如您所说)并使用 fgets() 进行捕捉,请改用它。它更紧凑:

    #include <stdio.h>
    
    int main(void) 
    {
        char word1[50], word2[50], line_text[50];
    
        while (fgets(line_text, sizeof(line_text), stdin))
        { 
            sscanf(line_text, "%s %s", word1, word2);
            printf("%s %s\n", word1, word2);
        }
    
        return 0;
    }
    

    输入:

    hello world
    dog cat
    black white
    apple banana
    

    输出:

    hello world 
    dog cat
    black white
    apple banana
    

    【讨论】:

      【解决方案2】:

      您的word1[line] 仅有 1 个字符长度的缓冲区。您应该分配字符数组的数组。

      别忘了打印每一行。

      #include <stdio.h>
      int main() 
      {
          char word1[21][5005], word2[21][5005], text[5005];
          int line = 0, i;
          while (fgets(text, sizeof(text), stdin))
          { 
              sscanf(text, "%s %s", word1[line], word2[line]);
              line++;
          }
          for(i = 0; i < line; i++)
             {
                 printf("%s %s", word1[i], word2[i]);
                 printf("\n");
              }
          return 0;
      }
      

      【讨论】:

      • 当输入包含超过 21 行时,这会出现严重问题。
      猜你喜欢
      • 1970-01-01
      • 2014-02-16
      • 2017-07-12
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      相关资源
      最近更新 更多