简体   繁体   English

Getline只读取第一行(或第一行)

[英]Getline only read the first row ( or first line)

my code: 我的代码:

string mess;    
getline(cin,mess);

and my txt file: 和我的txt文件:

hello james\n
how are \n
you.

when i am using getline. 当我使用getline时。 it just read in hello james. 它只是在你好詹姆斯读。 Is there a way that i can read "how are you"? 有没有办法让我读“你好吗?”

You can tell std::getline() to read up to a specific character. 您可以告诉std::getline()读取特定字符。 Assuming the character isn't in the stream, it will read the entire stream, eg 假设该字符不在流中,它将读取整个流,例如

std::string mess;
if (std::getline(std::cin, mess, '\0')) {
    // ...
}
else {
    std::cout << "ERROR: failed to read input\n";
}

If you need to read in exactly two lines, you'll probably best of using std::getline() twice and combining the result, probably with an intervening "\\n" . 如果你需要读两行,你可能最好两次使用std::getline()并结合结果,可能是干预"\\n"

I am not sure if you are open for other ways to solve the problem or if you have restrictions so that you need to use getline to read the whole file. 我不确定您是否对其他解决问题的方法持开放态度,或者您是否有限制因此需要使用getline来读取整个文件。 If not I find this a nifty way to put the contents of a text-file in memory to process it further. 如果不是,我发现这是一种将文本文件的内容放入内存以进一步处理它的好方法。

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();

now you should have the whole file in the variable my_string . 现在你应该将整个文件放在变量my_string

If you wish to read the entire file you can use the function read() (See reference here ) 如果您希望读取整个文件,可以使用函数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);

If you wish to read just those 2 lines, then its easier to use getline twice. 如果你只想阅读那两行,那么它更容易使用两次getline

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM