cin作为产生垃圾值的变量名

Shi*_*ora -4 c++ namespaces keyword

对于以下代码:

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

我期望输出为:

cin : <input>
Run Code Online (Sandbox Code Playgroud)

但输出是:

cin : <junk value>
Run Code Online (Sandbox Code Playgroud)

πάν*_*ῥεῖ 7

好吧让我们剖析你的代码(using namespace std假设):

#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;
}
Run Code Online (Sandbox Code Playgroud)

有点证明


Ram*_*ama 5

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

以下示例适用于int输入:

#include <iostream>

int main ()
{
       int cin;
       std::cin >> cin;
       std::cout << "cin: " << cin;
       return 0;
}
Run Code Online (Sandbox Code Playgroud)

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

一个很好的建议,但offtopic可以测试std::cin::operator >>像这个链接的failbit 的结果