开发者

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

开发者 https://www.devze.com 2023-02-20 00:04 出处:网络
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 开发者_Python百科something different? I\'ve checked, but can\'t find anything.

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 开发者_Python百科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;
    }
}


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.


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


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


Cin only gets input for 1 word. In order to get input for a sentence, you need to use a getLine(cin, y) in order to get a sentence of input. You can also make multiple variables for each word and then tyou use cin to get the input like this cin >> response1, response2, response3, response3, etc;.

0

精彩评论

暂无评论...
验证码 换一张
取 消