我的代码:
string mess;
getline(cin,mess);
和我的txt文件:
hello james\n
how are \n
you.
当我使用getline时。它只是在你好詹姆斯读。有没有办法让我读“你好吗?”
答案 0 :(得分:2)
您可以告诉std::getline()
读取特定字符。假设该字符不在流中,它将读取整个流,例如
std::string mess;
if (std::getline(std::cin, mess, '\0')) {
// ...
}
else {
std::cout << "ERROR: failed to read input\n";
}
如果您需要完全阅读两行,您可能最好两次使用std::getline()
并结合结果,可能会介入"\n"
。
答案 1 :(得分:0)
我不确定您是否对其他解决问题的方法持开放态度,或者您是否有限制因此需要使用getline
来读取整个文件。如果不是,我发现这是一种将文本文件的内容放入内存以进一步处理的好方法。
ifstream ifs (filename, ios::in);
if (!ifs.is_open()) { // couldn't read file.. probably want to handle it.
return;
}
string my_string((istreambuf_iterator<char>(ifs)), istreambuf_iterator<char>());
ifs.close();
现在您应该将整个文件放在变量my_string
。
答案 2 :(得分:0)
如果您希望阅读整个文件,可以使用read()
功能(参见参考here)
std::ifstream f (...);
// get length of file:
f.seekg (0, f.end);
int length = f.tellg();
f.seekg (0, f.beg);
char * buffer = new char [length];
// read data as a block:
f.read (buffer,length);
如果您只想阅读这两行,那么它更容易使用getline
两次。