c++ - 如何循环一个类变量数组?
问题描述
仅供参考,我声明了一个类调用 UC,在 UC 内部我声明了一个变量调用course
及其数组 [4],这与我现在面临的问题有关。转到我评论为问题的行,我现在只知道该行for(UC &i :: one.course)
是错误的,尤其是 UC,这行代码应该做一个 forloopcourse[4]
但它没有,它只是显示错误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、室内设计、大众传播、商业
//这条线不起作用
解决方案
您的问题部分可以如下所示,使用 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 循环中并打印出数组元素。
推荐阅读
- python - 安装 Python 包 PCAPY 时出错
- apache-nifi - Windows机器上的apache nifi 1.7.1重启问题
- jquery - jQuery - 匹配具有相同数据的元素
- javascript - 附加文件后动态更改回形针图标,改为显示文件图标。
- javascript - 如何使用 ajax 读取外部 docx 文件内容
- javascript - 如何获取 Chrome 浏览器的所有传入 IP 连接列表?
- python - 如何访问jinja2.Template的环境
- python - 如何在 Django 管理自定义列中获取请求参数?
- php - Wordpress PHP - 你如何将帖子缩略图移动到帖子标题和摘录下方
- python - 如何测试更复杂的功能?