我想将字符串数组声明为用户提供的限制。所以我在 getData() 中取了限制,并在 getData 函数中声明了字符串。总的来说,我想取学生的名字并将其显示在同一个班级中。对不起,基本问题,提前谢谢你。
class student
{
int limit;
public:
void getData()
{
cout<<"Enter the number of students: ";
cin>>limit;
string name[limit];
cout<<"Enter the names of students: \n";
for(int i=0; i<limit; i++)
cin>>name[i];
}
void showData()
{
cout<<"The list of students: \n";
for(int i=0; i<limit; i++)
cout<<name[i]<<endl;
}
};
int main()
{
student s1;
s1.getData();
s1.showData();
return 0;
}
在此函数中,错误来自“名称未在此范围内声明”。如果是废话,请提前道歉。
void showData()
{
cout<<"The list of students: \n";
for(int i=0; i<limit; i++)
cout<<name[i]<<endl;
}
您的代码的一个问题是在string name
中定义getData()
但不在showData()
. 我要做的是声明一个成员变量vector<string> name
,就像你对int limit
. 我会使用向量而不是数组,因为它更容易为我编写代码。
#include <iostream>
#include <vector>
using namespace std;
class student
{
int limit;
vector<string> name;
public:
void getData()
{
cout<<"Enter the number of students: ";
cin>>limit;
cout<<"Enter the names of students: \n";
for(int i=0; i<limit; i++)
{
string temp;
cin>>temp;
name.push_back(temp);
}
}
void showData()
{
cout<<"The list of students: \n";
for(int i=0; i<limit; i++)
cout<<name[i]<<endl;
}
};
int main()
{
student s1;
s1.getData();
s1.showData();
return 0;
}
输出:
Enter the number of students: 3
Enter the names of students:
andy
max
rose
The list of students:
andy
max
rose
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句