How to read a complete line from the user using cin?

独自空忆成欢 提交于 2019-11-26 04:56:00

问题


Here is my current C++ code. I would like to know how to write a line of code. Would I still use cin.getline(y) or something different? I\'ve checked, but can\'t find anything. When I run it, it works perfectly except it only types one word instead of the full lines I need it to output. This is what I need help with. I\'ve outlined it in the code.

Thanks for helping

#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;
    }
}

回答1:


The code cin >> y; only reads in one word, not the whole line. To get a line, use:

string response;
getline(cin, response);

Then response will contain the contents of the entire line.




回答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;
}



回答3:


string str;
getline(cin, str);
cin >> ws;

You can use getline function to read the whole line instead of reading word by word. And The cin>>ws is there to skip white spaces. And you find some detail about it here : http://en.cppreference.com/w/cpp/io/manip/ws



来源:https://stackoverflow.com/questions/5455802/how-to-read-a-complete-line-from-the-user-using-cin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!