0
#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;
} 

OutPut :

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

Compiled on Visual-Studio-Code(on linux os) what should i do to get correct output.

4

2 回答 2

1

您声明了两个类型的对象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;
于 2019-10-05T13:22:05.020 回答
1

因为您使用的是未初始化的struct

struct student s; 

它隐藏了全局s.

相反,将其初始化为main

student s = {"Karthik",1,95.3};
于 2019-10-05T13:19:05.117 回答