C++ 显示字符串时出现问题。字符串字段显示为空
在显示功能中,除以字符串格式给出的名称外,所有详细信息均正确显示。为什么字符串有时不能正确显示C++ 显示字符串时出现问题。字符串字段显示为空,c++,string,C++,String,在显示功能中,除以字符串格式给出的名称外,所有详细信息均正确显示。为什么字符串有时不能正确显示 #include<iostream> #include<string> using namespace std; struct student{ string n; int r; //taking details in void details(){ student s; cout<<"enter
#include<iostream>
#include<string>
using namespace std;
struct student{
string n;
int r;
//taking details in
void details(){
student s;
cout<<"enter name of student"<<endl;
cin >>s.n;
cout<<"enter roll no of student"<<endl;
cin >>s.r;
}
//display details
void display(){
student s;
cout<<"name of the student : "<<s.n<<endl;
cout<<"roll no of the student : "<<s.r<<endl;
}
};
int main(){
int x,i;
cout<<"enter no. of students : "<<endl;
cin>>i;
student s[10];
for(x=0;x<i;x++) {
s[x].details();
}
for(x=0;x<i;x++) {
s[x].display();
}
}
#包括
#包括
使用名称空间std;
结构学生{
字符串n;
INTR;
//详细记录
无效详细信息(){
学生证;
coutdetails()
创建一个临时对象student s;
并写入其值,而不修改调用它的实例。函数结束后,此临时对象s
将被丢弃,并且没有任何更改。同样地,显示
将打印(空)默认构造的临时对象的值
在details()
中,您要修改当前实例,由this
指向:
void details(){
cout<< "enter name of student"<<endl;
cin >> this->n;
cout<< "enter roll no of student"<<endl;
cin >> this->r;
}
void详细信息(){
coutn;
库特;
}
同样地,display
()应该打印this->n
和this->r
尽管这里不需要这个
,但我想说清楚。建议:将void details()
更改为bool details()
并返回cin
的状态。通常,始终测试IO事务的结果,以便处理故障。这对于用户输入尤其重要,因为人类是出了名的不可靠输入源。建议:更喜欢给变量起描述性名称。良好的命名使代码实际上记录了自身,mak阅读和理解代码很容易。也很难意外地引入一个难以识别的打字错误,比如用仍然可以编译的n
替换r
。如果标识符是一个完整的单词,拧错一个字母通常会导致编译错误。将r
替换为n
你可能只能o在运行时和浪费时间调试程序后发现错误。@Tanmai真的考虑到了上面的两条评论^。他非常聪明。在给出描述性名称时,这确实使代码更清晰。这使您的生活和其他人阅读代码更容易。