我正在尝试将由 cin 命令设置的字符串写入文件。我让它工作,但它并没有写出所有的字符串;只是第一个空白之前的所有内容。所以有人建议我使用:
Write_Test << getline( Text , cin );
让它接受空格,但正如标题所说我不能使用 getline?
所有代码:
string Text;
cout << "Write something: ";
cin >> Text;
if (Text != "")
{
ifstream Write_Test("Write_Test.txt");//Creating the file
//Write_Test << Text; //Write a message to the file.
Write_Test << getline( Text , cin );
Write_Test.close(); //Close the stream, meaning the file will be saved.
cout << "Done!";
}
感谢您的帮助!
最佳答案
首先,你可能打算写
std::getline(std::cin, Text)
此表达式采用 std::istream&
并返回此 std::istream&
。假设你得到了 getline()
的参数,表达式
out << std::getline(std::cin, Text)
实际上是将std::cin
的流状态写入out
。这可能是您想要的,但我猜您实际上是想使用
if (std::getline(std::cin, Text)) {
WriteTest << Text;
}
这应该将从 std::cin
读取的一行文本写入 WriteTest
。
一个完整的程序看起来像这样:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
int main()
{
std::ofstream out("WriteTest.txt");
if (!out) {
std::cout << "Error: failed to open output file\n";
return EXIT_FAILURE;
}
std::string text;
if (std::getline(std::cin, text)) {
out << text << '\n';
}
else {
std::cout << "Error: failed to read a line\n";
}
关于c++ - 写入文件时不能使用 getline?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18923051/