【问题标题】:cin as a variable name producing garbage valuecin 作为产生垃圾值的变量名
【发布时间】:2017-12-01 00:35:32
【问题描述】:

对于以下代码:

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

我预计输出是:

cin : <input>

但是输出是:

cin : <junk value>

【问题讨论】:

  • 这就是为什么你不应该使用:using namespace std;
  • int x; x &gt;&gt; x; cout &lt;&lt; x;一样,没有意义。另一方面,std::cin &gt;&gt; cin 会起作用。
  • @ChristopherPisz 其实是compiles fine
  • 这个问题应该被赞成并保留作为参考为什么一个人永远不应该成为using namespace std;
  • @ShivamArora 请包含您的完整程序,以便我们有MCVE 没有任何答案都是猜测

标签: c++ namespaces keyword


【解决方案1】:

好的,让我们剖析您的代码(假设为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;
}

Kinda proof

【讨论】:

  • 你能解释一下我在哪里使用 using namespace std; 会遇到麻烦吗
  • @ShivamArora 人们猜测你认为cin &gt;&gt;中的cin指的是std::cin
  • 没有问题的情况下你是如何回答的?为什么要提供无法编译的代码? cout 不符合 std:: 并且您没有包含 在任何支持 C++11 的编译器上,输出是 'cout' : undeclared identifier。
  • @ChristopherPisz 我不想参加毫无意义的战斗,但我在进行任何编辑之前看到了原始答案,并且它有一条说明它假设存在using namespace std;。我同意这个问题应该先改进,然后才能正确回答,但我认为你有点反应过度
【解决方案2】:

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

以下示例适用于 int 输入:

#include <iostream>

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

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

还有一个很好的建议,但题外话可能是用这样的故障位测试std::cin::operator &gt;&gt; 的结果link

【讨论】:

  • 谢谢拉玛。我不知道为什么人们仍然拒绝投票感谢您的宝贵时间
  • 这是一个修复,但并没有真正解释为什么 OPs 代码会产生它所产生的输出
  • @ShivamArora 您的问题被否决了,因为它不是一个很好的问题。是的,这是一个问题,但它是如此基本的问题,你可以拿起一本基本的 C++ 书,阅读第一章,然后找出你的问题是什么。你表明你没有做任何研究,也没有理解你写的东西。
  • @tobi303 谢谢!,添加解释
  • @ChristopherPisz 谢谢,添加了有关故障位检查的建议
猜你喜欢
  • 2016-12-31
  • 1970-01-01
  • 2015-05-24
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-17
相关资源
最近更新 更多