[英]Cant use getline when writing to a file?
I am trying to write a string set by the cin command to a file. 我试图将cin命令设置的字符串写入文件。 I have it working, but it is not writing all of the string; 我有它工作,但它不是写所有的字符串; just everything ebfore the first white space. 只是第一个白色空间之前的一切。 So someone suggested I use: 所以有人建议我使用:
Write_Test << getline( Text , cin );
To make it accept white spaces, but as the title says I cant use getline? 为了让它接受白色空格,但正如标题所说,我不能使用getline?
All code: 所有代码:
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!";
}
Thanks for any help! 谢谢你的帮助!
First of all, you probably meant to write 首先,你可能想写
std::getline(std::cin, Text)
This expression take an std::istream&
and returns this std::istream&
. 这个表达式采用std::istream&
并返回此std::istream&
。 Assuming you got the arguments of getline()
right, the expression 假设你得到了getline()
的参数,表达式
out << std::getline(std::cin, Text)
actually write the stream state of std::cin
to out
. 实际上将std::cin
的流状态写入out
。 This may be what you wanted but my guess is that you actually meant to use 这可能是你想要的,但我的猜测是你真的想要使用
if (std::getline(std::cin, Text)) {
WriteTest << Text;
}
This should write a line of text read from std::cin
to WriteTest
. 这应该写一行从std::cin
读取到WriteTest
的文本。
A complete program would look something like this: 一个完整的程序看起来像这样:
#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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.