【问题标题】:How to read a complete line from the user using cin?如何使用 cin 读取用户的完整行?
【发布时间】:2011-07-24 06:29:58
【问题描述】:

这是我当前的 C++ 代码。我想知道如何编写一行代码。我还会使用cin.getline(y) 还是其他的?我检查过,但找不到任何东西。 当我运行它时,它工作得很好,除了它只输入 one 单词而不是我需要它输出的完整行。这是我需要帮助的。我已经在代码中对其进行了概述。

感谢您的帮助

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>

using namespace std;

int main()
{
    char x;

    cout << "Would you like to write to a file?" << endl;
    cin >> x;
    if (x == 'y' || x == 'Y')
    {
        char y[3000];
        cout << "What would you like to write." << endl;
        cin >> y;
        ofstream file;
        file.open("Characters.txt");
        file << strlen(y) << " Characters." << endl;
        file << endl;
        file << y; // <-- HERE How do i write the full line instead of one word

        file.close();


        cout << "Done. \a" << endl;
    }
    else
    {
        cout << "K, Bye." << endl;
    }
}

【问题讨论】:

  • 您可能想让您的标题更好地反映您的问题。另外,你应该澄清你的问题,你问的不是很清楚。
  • 问题是cin &gt;&gt; y只存储用户键入的行的第一个单词,提问者想知道如何将整行存储在y中,这样file &lt;&lt; y会写完整文件的行。

标签: c++ iostream


【解决方案1】:

代码cin &gt;&gt; y; 只读取一个单词,而不是整行。要获得一条线,请使用:

string response;
getline(cin, response);

那么response将包含整行的内容。

【讨论】:

    【解决方案2】:
    #include <iostream>
    #include <cstdlib>
    #include <cstring>
    #include <fstream>
    #include <string>
    
    int main()
    {
        char write_to_file;
        std::cout << "Would you like to write to a file?" << std::endl;
        std::cin >> write_to_file;
        std::cin >> std::ws;
        if (write_to_file == 'y' || write_to_file == 'Y')
        {
            std::string str;
            std::cout << "What would you like to write." << std::endl;
    
            std::getline(std::cin, str);
            std::ofstream file;
            file.open("Characters.txt");
            file << str.size() << " Characters." << std::endl;
            file << std::endl;
            file << str;
    
            file.close();
    
            std::cout << "Done. \a" << std::endl;
        }
        else
            std::cout << "K, Bye." << std::endl;
    }
    

    【讨论】:

    • 重要的部分是:getline(std::cin, y); 而不是 cin &gt;&gt; y;
    • 你还需要 cin >> ws;否则 getline 只会读取一个新行
    • 在编写代码作为问题的答案时,请从不使用using namespace std;(实际上你几乎不应该这样做,尤其是在可能被阅读的帖子中)完全是初学者,然后他们拿起它并认为它是可以的)。答案中发布的代码应该是一个很好的例子。
    【解决方案3】:
    string str;
    getline(cin, str);
    cin >> ws;
    

    您可以使用 getline 函数来读取整行而不是逐字读取。 cin>>ws 可以跳过空格。您可以在此处找到有关它的一些详细信息: http://en.cppreference.com/w/cpp/io/manip/ws

    【讨论】:

    • 非常感谢您的建议,我已经编辑了答案。
    【解决方案4】:

    Cin 只能输入 1 个单词。为了获得一个句子的输入,您需要使用getLine(cin, y) 来获得一个句子的输入。您还可以为每个单词创建多个变量,然后使用 cin 来获取像 cin &gt;&gt; response1, response2, response3, response3, etc; 这样的输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多