【问题标题】:Multiple line input by gets() function in c++c++中gets()函数的多行输入
【发布时间】:2017-03-15 18:08:10
【问题描述】:

当我编写此代码时,我无法通过 gets() 函数输入两行作为输入,其中每行包含 3 到 5 个单词:

int main()
{
    int t;
    cin>>t;
    char nm1[50],nm2[50];
    while(t--)
    {
       gets(nm1);
       gets(nm2);

       puts(nm1);
       puts(nm2);

    }
}

但是当我在 while() 函数之前添加一个 gets() 函数时,现在我可以输入两行这样的字符串:

int t;
cin>>t;
char nm1[50],nm2[50];
gets(nm1); //using gets() function here//
while(t--)
{
   gets(nm1);
   gets(nm2);

   puts(nm1);
   puts(nm2);
}

那么,这背后的逻辑是什么?

【问题讨论】:

  • 不要在 C++ 中使用gets。它在 C++11 中已弃用,并在 C++14 及更高版本中被删除。
  • gets 函数很危险,因为它会溢出缓冲区。如果必须,请改用fgets。更喜欢在 C++ 中使用 std::string 来处理文本。
  • 因为我必须输入两行,每行包含五个单词。
  • 你的main函数应该返回一个值给操作系统,比如0代表成功,其他数字代表失败。

标签: c++ c++11 char


【解决方案1】:
  1. 不要使用gets。见Why gets() is deprecated?
  2. 不要将cinstdio.h 中的函数混用。默认情况下,cinstdin 同步。但是,可以使用

    使它们保持不同步
    std::ios_base::sync_with_stdio(false);
    

    更多详情请参阅http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio

真正的问题。

cin >> t;

在输入流中留下一个换行符。对gets 的下一次调用会读取该内容。如果您不希望 gets 读取该内容,则必须添加代码以读取并丢弃该行的其余部分。

这是我的建议:

int main()
{
   int t;
   cin >> t;

   // Ignore the rest of the line.
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

   char nm1[50],nm2[50];
   while(t--)
   {
      cin.get(nm1, 50);
      cin.get(nm2, 50);

      puts(nm1);
      puts(nm2);
   }
}

一定要dd

#include <limits>

能够使用std::numeric_limits

【讨论】:

  • "不要混合 cin 和 stdio.h 中的函数。"请准确说明为什么不这样做 - 从技术上讲,它是完全安全的;如果不是这样,很多 C++ 代码将无法工作。
  • 当需要一个单词时,您是否建议阅读整行?
  • @ThomasMatthews,不,我不知道。我认为我没有提出这个建议。
【解决方案2】:

cin&gt;&gt;t中你输入了一个数字然后按下回车\n,而行尾仍在缓冲区中等待,如果你读取另一个整数cin&gt;&gt;another_integercin将忽略\n' '(空格),但不会获取。您真正输入的内容类似于以下内容

5\n ---- 看到行尾了吗?
我的字符串\n
我更大的字符串\n

gets() 读取直到找到\nend of file

顺便说一句,gets() 在 c++11 中已被弃用,你应该使用 getline() 或其他函数来代替

【讨论】:

    【解决方案3】:

    我强烈建议使用 C++ 结构执行更安全的 I/O:

    int main()
    {
      unsigned int quantity;
      cin >> quantity;
      // Now input the words
      std::vector<std::string> database;
      while (cin >> word)
      {
        database.push_back(word);
      }
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      • 2021-11-23
      • 2012-01-08
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      相关资源
      最近更新 更多