【问题标题】:Showing Garbage values in Structures in c++在 C++ 中的结构中显示垃圾值
【发布时间】:2020-02-03 12:22:28
【问题描述】:
#include<iostream>
using namespace std;
struct student
{
  char name [50];
  int roll;
  float marks;
}s = {"Karthik",1,95.3};
int main()
{
  struct student s;
  cout<<"\nDisplaying Information : "<<endl;
  cout<<"Name  : "<<s.name<<endl;
  cout<<"Roll  : "<<s.roll<<endl;
  cout<<"Marks : "<<s.marks<<endl;
   return 0;
} 

输出:

Displaying Information : 
Name  : 
Roll  : 21939
Marks : 2.39768e-36

在 Visual-Studio-Code 上编译(在 linux 操作系统上) 我应该怎么做才能得到正确的输出。

【问题讨论】:

  • 强制提醒 char name[50]; 不应在 C++ 中用作字符串。我们有std::strings。

标签: c++ visual-studio-code scope g++ global-namespace


【解决方案1】:

因为你使用的是这个未初始化的struct

struct student s; 

它隐藏了全局s

相反,将其初始化为main:

student s = {"Karthik",1,95.3};

【讨论】:

    【解决方案2】:

    您声明了两个 student 类型的对象。

    第一个在全局命名空间中声明

    struct student
    {
      char name [50];
      int roll;
      float marks;
    }s = {"Karthik",1,95.3};
    

    并且被初始化并且在函数main的块范围内的第二个

    struct student s;
    

    而且还没有初始化。

    块作用域中声明的对象隐藏了全局命名空间中声明的同名对象。

    要么删除本地声明,要么使用限定名称来指定在全局命名空间中声明的对象,例如

      cout<<"\nDisplaying Information : "<<endl;
      cout<<"Name  : "<< ::s.name<<endl;
      cout<<"Roll  : "<< ::s.roll<<endl;
      cout<<"Marks : "<< ::s.marks<<endl;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-10
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      相关资源
      最近更新 更多