仅供参考,我声明了一个类调用UC,在UC中我声明了一个变量调用course
及其一个数组[4],这与我现在面临的问题有关。转到我评论为问题的行,我现在所知道的是行for(UC &i :: one.course)
是错误的,尤其是UC,这行代码应执行course[4]
的forloop,但事实并非如此,只是显示类似i has not been declared
的错误。我的预期输出就在那儿。
#include <iostream>
#include <string>
using namespace std;
class UC{
public:
string name;
int history;
string founder;
string course[4];
};
void print(string, int, string);
int main()
{
UC one;
one.name = "ABC";
one.history = 5;
one.founder = "Mr.Chong";
one.course[0] = "IT";
one.course[1] = "Interior Design";
one.course[2] = "Mass Comm";
one.course[3] = "Business";
print(one.name, one.history, one.founder);
cout<<"Our Course: ";
//problem here//
string delim = "";
for(UC &i :: one.course){
cout<< delim <<i;
delim = ", ";
};
//problem here//
return 0;
}
void print(string r, int x, string y){
cout<<"Our College Name: "<<r<<endl;
cout<<"Our History: "<<x<<endl;
cout<<"Our Founder: "<<y<<endl;
};
我希望输出会像
我们的大学名称:ABC
我们的历史:5
我们的创始人:庄先生
我们的课程:IT,室内设计,大众传播,商业
//此行不起作用
答案 0 :(得分:0)
您的问题部分可以如下所示,以使用for循环打印出一个数组:
#include <iostream>
#include <string>
using namespace std;
class UC{
public:
string name;
int history;
string founder;
string course[4];
};
void print(string, int, string);
int main()
{
UC one;
one.name = "ABC";
one.history = 5;
one.founder = "Mr.Chong";
one.course[0] = "IT";
one.course[1] = "Interior Design";
one.course[2] = "Mass Comm";
one.course[3] = "Business";
print(one.name, one.history, one.founder);
cout<<"Our Course: ";
//problem here
int numberofelements = sizeof(one.course)/sizeof(one.course[0]);
for (int i = 0; i < numberofelements; i++){
if(i == numberofelements-1){
cout << one.course[i];
}
else{
cout << one.course[i] << ", ";
}
}
// problem here
return 0;
}
void print(string r, int x, string y){
cout<<"Our College Name: "<<r<<endl;
cout<<"Our History: "<<x<<endl;
cout<<"Our Founder: "<<y<<endl;
};
或者,如果您想要一种更简洁的方法,则可以修改void print方法,以采用将传递到方法主体中的for循环中的数组参数并打印出数组元素。