c++ - 为什么要避免 C++ 中的输入运算符(operator>>)?

标签 c++ input operators

this question接受答案的作者不推荐使用输入运算符,因为:

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

但这意味着什么?为什么我们在用 C++ 编程时要避免使用 C++ 的输入运算符?

我从 The Definitive C++ Book Guide and List 读过的书没有提到这一点,他们引入并使用了输入运算符。我也没有在互联网上找到任何关于这个主题的有用信息。

谢谢!

p.s:很抱歉,我没有足够的声望在该主题中提出我的问题。

最佳答案

我唯一能想到的是 operator>> 在使用之间保留了很多设置。例如:

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

someOtherFunction(fin);

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

除非我们考虑,否则看起来很无辜:

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

我亲自阅读了原始文件并使用正则表达式进行解析,但我绝不是该主题的专家,因此应该谨慎对待建议。

关于c++ - 为什么要避免 C++ 中的输入运算符(operator>>)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21155395/

相关文章:

python - 如果既不是按位运算也不是 print chevron,>> 是做什么的?

java -++ 运算符在 Java 中

c++ - 放置指向 shared_ptr 的多重映射的指针不起作用

c++ - 在 C++ 中读取 excel 表的单元格

typescript - Ionic 2 获取 ionic 输入值

C# - 如何阻止在按键时输入字母?

php - 提交表单后如何使下拉菜单值仍处于选中状态?

c++ - 哪个运营商删除?

c++ - 有 union 的 union 这样的东西吗?

C++ 数组循环问题仍然需要帮助