简体   繁体   English

看到'-'字符时我无法结束getline,有人可以帮助我getline()ifstream in c ++

[英]I cant end getline when see ' - ' character, can someone help me getline() ifstream in c++

ifstream InPut;
ofstream OutPut;
InPut.open("/Users/apple/Documents/Lập trình C++/OOP/Tập tin/Test1/Test1/FileIn.txt",ios_base::in);

string str, mssv;

getline(InPut,str);
InPut.seekg(1,ios_base::cur);
getline(InPut,mssv);
InPut.close();
cout<<""<<str<<"/"<<mssv;
return 0;

FileIn.txt: FileIn.txt:

Nguyen Xuan Sang-1520159 阮宣生-1520159

I just want to read "Nguyen Xuan Sang", but my code reads in all of FileIn.txt. 我只想阅读“阮宣尚”,但我的代码读取了所有FileIn.txt。

Computers can't read your mind. 电脑看不懂你的想法。 You never told it to read to the "-", so the computer has no way of knowing at all if you want to read until a space, line break, or something else. 您从未告诉过它要读到“-”,因此计算机根本无法知道您是否要阅读,直到空格,换行符或其他内容为止。

Imagine that you want to read to some other character. 假设您想阅读其他字符。 How would your code be different? 您的代码会有什么不同? If there is no difference, you are doing something wrong. 如果没有区别,则说明您做错了。

getline() defaults to using a nextline as the delimiter, which in your case seems to cause it to read the whole file. getline()默认使用下一行作为分隔符,在您看来,这似乎导致它读取整个文件。

To tell getline() to read until a "-", specify the character as the third argument like this: 要告诉getline()读取到一个“-”,请将该字符指定为第三个参数,如下所示:

getline(InPut, str, '-');

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

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