C++ GIS- 243030403和300 \ 371个数
我的输入是正常的数字和名称,比如12345,Joe,但输出的是所有奇怪的数字,比如-274344232和\300\230\340C++ GIS- 243030403和300 \ 371个数,c++,arrays,C++,Arrays,我的输入是正常的数字和名称,比如12345,Joe,但输出的是所有奇怪的数字,比如-274344232和\300\230\340 using namespace std; struct student{ int Id; string name; }; void display(student *x){ int i; for( i=0; i<5; i++){ cout<<"student id : "<
using namespace std;
struct student{
int Id;
string name;
};
void display(student *x){
int i;
for( i=0; i<5; i++){
cout<<"student id : "<<x->Id<<endl;
cout<<"student name : "<<x->name<<endl;
}
}
int main(){
student stu[5];
int i;
for( i=0; i<5; i++){
cout<<"enter the student id ";
cin>>stu[i].Id;
cout<<"enter the name of student : ";
cin>>stu[i].name;
}
display(&stu[5]);
return 0;
}
线路
display(&stu[5]);
导致未定义的行为。请记住,在大小为5的数组中,4是访问该数组的最大有效索引
换成
display(&stu[0]);
或者干脆
display(stu);
再
但如果我改为&stu[0],它将输出相同的id和名称5次 答案是,考虑到你发布的代码,是的。您需要将显示更新为 显示与数组中所有元素对应的数据。此行显示&stu[5];是什么引起的 你是说stu有第五个索引,但它没有 定义由5个元素组成的数组时。你只有一个0,1,2,3,4的索引
因此,请改为放置、显示&stu[0]。这是否回答了您的问题?pass displaystustu[5]是数组末尾的一个。有关更多信息,请参见链接的重复问题cin>>stu[i].name;在您修复display&stu[5];之后,这可能是您的问题的一部分;。确保他们没有输入名字和姓氏。请记住,如果键入一个空格,第一个空格前的部分将进入名称,其余部分将输入到下一个Idbut,但如果我更改为&stu[0],它将输出相同的id和名称5次?为什么使用。而不是->@newLearner x[i]不是指针,所以需要->。有关C++为什么不为指针的详细信息,请参阅C++编程文本。
void display(student *x){
int i;
for( i=0; i<5; i++){
cout << "student id : " << x[i].Id << endl;
cout << "student name : " << x[i].name << endl;
}
}