如何使用cin从用户那里读取完整的一行?

Fuz*_*Ski 18 c++ iostream

这是我目前的C++代码.我想知道如何编写一行代码.我还会使用cin.getline(y)或不同的东西吗?我已经检查过,但找不到任何东西.当我运行它时,它完美地工作,除了它只键入一个单词而不是我需要输出的整行.这是我需要帮助的.我在代码中概述了它.

谢谢你的帮助

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

yba*_*kos 67

代码cin >> y;只读一个字,而不是整行.要获得一条线,请使用:

string response;
getline(cin, response);
Run Code Online (Sandbox Code Playgroud)

然后response将包含整行的内容.


hid*_*yat 9

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • 当编写代码作为问题的答案时,请执行*never*使用`using namespace std;`(实际上你几乎不应该这样做,但特别是在初学者可能会阅读的帖子中,然后他们会把它拿起来认为没关系).答案中张贴的代码应该是一个很好的例子. (10认同)
  • 重要的部分是:`getline(std :: cin,y);`而不是`cin >> y;`. (3认同)

Yin*_*Guo 5

string str;
getline(cin, str);
cin >> ws;
Run Code Online (Sandbox Code Playgroud)

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