我正在处理以下代码.
#include <iostream>
int main()
{
std::cout << "Enter numbers separated by whitespace (use -1 to quit): ";
int i = 0;
while (i != -1) {
std::cin >> i;
std::cout << "You entered " << i << '\n';
}
}
Run Code Online (Sandbox Code Playgroud)
我知道使用while (std::cin >> i)本来会更好,但我不明白具体的情况.如果我提供无效输入,则循环变为无限,因为输入流进入故障位状态.我的问题是输入变量会发生什么i?就我而言,无论先前输入的值如何,它都变为0.输入无效后为什么会变为0?这是预定义的行为吗?
以下函数是从C++ Primer,第5版和第214页编写的.此函数将返回字符串中第一次出现给定字符的位置,并告知该字符串中该字符的出现次数.
string::size_type find_char(const string &s, char c, string::size_type &occurs)
{
// Compares the given character with string
// Records the first occurrence of that character
// The change in &occurs is reflected back to the original variable
}
Run Code Online (Sandbox Code Playgroud)
作者建议在传递参数时使用"避免副本const参考",并对函数不变的参数使用" 参考参数".为什么他们不把char c一个const基准参数?