简体   繁体   中英

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:

Nguyen Xuan Sang-1520159

I just want to read "Nguyen Xuan Sang", but my code reads in all of 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.

To tell getline() to read until a "-", specify the character as the third argument like this:

getline(InPut, str, '-');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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