我正在尝试学习C ++,但是我有些困惑。
我正在使用Geany和CentOS创建基本的成绩簿应用程序。
Geany在应用程序的for和cout行上显示红色的卷曲线。我觉得一切都使用了正确的语法,但出现“编译失败。”
我的来源出了什么问题?
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main(void){
// Declaration of local variables for gradebook
vector<int> gradeVector;
char choice;
bool menu = true;
// User Menu
while (menu){
cout << "This is the gradebook menu\n";
cout << "Please enter (a) to Show All Grades\n";
cout << "Please enter (l) to Show Last Grade\n";
cout << "Please enter (g) to Add Grade\n";
cout << "Please type 0 to Exit.\n";
cin >> choice;
switch(choice){
case 'a':
for (i=0;i <= gradeVector.size(); i++)
cout << "These are the grades entered: \n"<<gradeVector.at(i);
break;
case 'l':
cout << "This was the last grade entered: \n" << gradeVector;
break;
case 'g':
cout << "Please add a grade to the gradebook: \n" << cin >> gradeVector.push_back();
break;
case 0:
menu = false;
break;
default:
cout << "Please ONLY use lower-case a, l, g, or 0 as your choice.\n"
}
}
return (0);
}
您的代码中存在多个错误。首先,您忘记声明整数i
。您尝试输出矢量,并且从您的文字中我收集到您只想要最后的成绩。输入应使用push_back进行,但应首先将其读入临时变量。更正此问题并更改一些通用代码将使您成为代码:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main(void){
// Declaration of local variables for gradebook
vector<int> gradeVector;
char choice;
bool menu = true;
// User Menu
while (menu){
cout << "This is the gradebook menu\n";
cout << "Please enter (a) to Show All Grades\n";
cout << "Please enter (l) to Show Last Grade\n";
cout << "Please enter (g) to Add Grade\n";
cout << "Please type 0 to Exit.\n";
cin >> choice;
switch(choice){
case 'a':
cout << "These are the grades entered: \n"
for (int i=0 ;i < gradeVector.size(); i++)
cout << gradeVector[i] << " ";
break;
case 'l':
cout << "This was the last grade entered: \n" << gradeVector[gradeVector.size()-1];
break;
case 'g':
cout << "Please add a grade to the gradebook: \n";
int input;
cin >> input;
gradeVector.push_back(input);
break;
case 0:
menu = false;
break;
default:
cout << "Please ONLY use lower-case a, l, g, or 0 as your choice.\n";
}
}
return (0);
}
对于一个,您的for循环语法是错误的。
for (i=0;i <= gradeVector.size(); i++)
每次都会给您一个segmentation fault,应该是
for (i=0;i < gradeVector.size(); i++)
因此,您不会访问超出范围的内存。请记住,计数从0开始,并且您访问的内存不能超过分配的内存。
您的编译错误在这里:
cout << "This was the last grade entered: \n" << gradeVector;
您不能引用这样的向量;您必须指出一个特定的元素。如果要删除向量中的所有元素,请使用for循环。