[英]Getline only read the first row ( or first line)
我的代码:
string mess;
getline(cin,mess);
和我的txt文件:
hello james\n
how are \n
you.
当我使用getline时。 它只是在你好詹姆斯读。 有没有办法让我读“你好吗?”
您可以告诉std::getline()
读取特定字符。 假设该字符不在流中,它将读取整个流,例如
std::string mess;
if (std::getline(std::cin, mess, '\0')) {
// ...
}
else {
std::cout << "ERROR: failed to read input\n";
}
如果你需要读两行,你可能最好两次使用std::getline()
并结合结果,可能是干预"\\n"
。
我不确定您是否对其他解决问题的方法持开放态度,或者您是否有限制因此需要使用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
。
如果您希望读取整个文件,可以使用函数read()
(参见此处的参考资料)
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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.