I have a question regarding what to do with "\\n"
or "\\r\\n"
etc. when reading a text file in C++. The problem exists when I do the following sequence of operations:
int k;
f>>k;
string line;
getline(f,line);
for an input file with something like
1
abc
I have to put a f.get()
in order to read off the ending "\\n"
after f>>k
. I even have to do f.get()
twice if I have "\\r\\n"
.
What is an elegant way of reading file like this if I mix >>
with getline
?
Thank you.
Edit Also, I wonder if there is any convenient way to automatically detect the given file has an end-of-line char "\\n"
or "\\r\\n"
.
You need to fiddle a little bit to >>
and getline
to work happily together. In general, reading something from a stream with the >>
operator will not discard any following whitspaces (new line characters).
The usual approach to solve this is with the istream::ignore
function following >>
- telling it to discard every character up to and including the next newline. (Only useful if you actually want to discard every character up to the newline though).
eg
#include <iostream>
#include <string>
#include <limits>
int main()
{
int n;
std::string s;
std::cout << "type a number: ";
std::cin >> n;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
std::cout << "type a string: ";
std::getline( std::cin, s );
std::cout << s << " " << n << std::endl;
}
edit (I realise you mentioned files in the question, but hopefully it goes without saying that std::cin is completely interchangable with an ifstream)
完全不同的方法是使用tr
预处理数据文件(假设您使用Linux)删除\\r
,然后使用getline()
。
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.