Qiang Li
Qiang Li

Reputation: 10865

read text file in C++

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

Upvotes: 2

Views: 1251

Answers (2)

suresh
suresh

Reputation: 1109

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

Upvotes: 0

Ben Cottrell
Ben Cottrell

Reputation: 6130

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)

Upvotes: 4

Related Questions