Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should you avoid input operator (operator>>) in C++?

In this question the author of the accepted answer does not recommend the usage of the input operator, because:

operator>> is subject to iomanip stream manipulators and other "funny" stuff, so you can never be sure that it does what's advertised.

But what does it mean? Why should we avoid the input operator of the C++ when we are programming in C++?

The books I have read from The Definitive C++ Book Guide and List did not mention this, they introduced and used the input operator. I have not found anything useful in this topic on the internet neither.

Thanks!

p.s: I am sorry, but I do not have enough reputation to ask my question in that topic.

like image 603
Gabor Meszaros Avatar asked Jan 16 '14 07:01

Gabor Meszaros


1 Answers

The only things I can think of are the fact that operator>> retains a lot of settings between uses. For example:

std::ifstream fin("input.txt");
std::string str;
double num;

someOtherFunction(fin);

while (fin >> str >> num)
{
   //do something
}

looks pretty innocent unless we consider:

void someOtherFunction(std::ifstream& fin){
    fin.width(1); 
    fin.setf(/* some flags here */); 
    //...
}

I personally read the file raw and do parsing with regex but I am by no means an expert on the subject so that advice should be taken with a big grain of salt.

like image 102
odinthenerd Avatar answered Nov 10 '22 21:11

odinthenerd