gpt4 book ai didi

c++ - Getline 只读第一个字

转载 作者:行者123 更新时间:2023-11-30 02:41:20 27 4
gpt4 key购买 nike

我是 C++ 的新手,我无法解决这个问题。 getline(cin, string) 只读取该行的第一个单词。

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

然后输入的文本被保存到文件中,但是当我尝试读取文件时,只保存了一个词,这是第一个词。我不确定以前是否有人问过这个问题,但我尝试使用高级搜索无济于事。

最佳答案

问题是您正在使用 >>> 来提取字符串。 >>> 字符串通常在空格处停止。

要读取整行,请执行您已经使用 cin 执行的操作——使用 getline:

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

关于c++ - Getline 只读第一个字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28211826/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com