cin作为变量名生成垃圾值

时间:2017-06-27 20:10:45

标签: c++ namespaces keyword

以下代码:

#include<iostream>
using namespace std;
int main ()
{
       int cin;
       cin >> cin;
       cout << "cin : " << cin;
       return 0;
}

我希望输出为:

cin : <input>

但输出是:

cin : <junk value>

2 个答案:

答案 0 :(得分:7)

好的,让我们剖析你的代码(#include <iostream> using namespace std; int main () { int cin; // Shadows the declaration of cin coming from the iostream header cin >> cin; // A bit shift operation on variable cin without capturing the result cout << "cin" << cin; // Output of the non initialized variable cin return 0; } 假设):

$ ant.sh compile

Kinda proof

答案 1 :(得分:5)

好的,这是你加入部队的白方并停止使用using namespace std;

的机会

以下示例适用于int输入:

#include <iostream>

int main ()
{
       int cin;
       std::cin >> cin;
       std::cout << "cin: " << cin;
       return 0;
}

为什么呢?在您的示例中,您的本地名称int cin将优先于cin std,并导致您的程序使用int变量进行UB而不进行初始化。

还有一个很好的建议,但是offtopic可以用这样的link

来测试std::cin::operator >>的结果。
相关问题