简体   繁体   中英

Getline only reads the first word

I'm new to C++ and I couldn't solve this problem. getline(cin, string) keeps reading only the first word of the line.

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

using namespace std;

string commitToFile, newTextFile, loadedText;

int main()
{
    cout << "Enter some text to save to a file." << endl;
    getline(cin, commitToFile);
    cout << "Enter a file name. Please do not use spaces." << endl;
    cin >> newTextFile;
    newTextFile.append(".tf");
    cout << "Saving..." << endl;
    ofstream saveText(newTextFile); //.tf stands for textfile
    if (!saveText) {
        cout << "Error!";
        return(0);
    }
    saveText << commitToFile << endl;
    saveText.close();
    cout << "Saved!" << endl;

    //opening the file
    cout << "Loading file..." << endl;
    ifstream loadText(newTextFile);
    loadText >> loadedText;
    loadText.close();
    cout << loadedText;
    return(0);
}

The entered text is then saved into a file, but when I try to read the file, only one word is saved, and this is the first word. I'm not sure if this has been asked before, but I've tried using the advanced search to no avail.

The problem is that you're using >> to extract the string. >> for strings normally stops on whitespace.

To read a whole line, do what you're already doing with cin —use getline :

cout << "Loading file..." << endl;
ifstream loadText(newTextFile);
getline(loadText, loadedText);
loadText >> loadedText;
loadText.close();
cout << loadedText;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM