2

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".

2 Answers 2

4

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).

e.g.

#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)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Please see my edit: so how to automatically write the statement std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); given sometimes I have "\r\n" as the ending characters?
@QiangLi it ignores all characters up-to and including the \n character. it doesn't matter what those characters are, there's nothing special about putting an \r in front of it so "\r\n" will be treated the same way as "\n" or "helloworld\t\n".
0

A completely different approach would be to pre-process the data file using tr (assuming that you use Linux) to remove \r and then use getline().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.