我是c ++的初学者,对c ++没有任何了解。我正在为学生和模块编写代码。要求是需要显示模块和学生的最终分数,也需要重复。当我编写案例5和案例6时,在编译之后它会显示以下错误。
错误C2360:初始化'代码'被' case'跳过标签 看到'代码的声明' 错误C2361:初始化'代码'被'默认'跳过标签 请参阅'代码'
的声明错误C2039:' getId' :不是' std :: vector< _Ty>'的成员 与[_Ty =学生]
错误C2039:' getModule' :不是' std :: vector< _Ty>'的成员 与[_Ty =学生]
Main.cpp的
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <vector>
#include "Student.h"
#include "Module.h"
using namespace std;
void printMenu();
vector<Student> readFile();
void liststudentRecord(vector<Student>);
string trim(string);
bool isValidClasscode(string s);
bool isvalidStudentid(string s);
bool test1Ascending(Student s1, Student s2);
bool test1Desscending(Student s1, Student s2);
bool test1finalScoreAscending(Student s1, Student s2);
vector<Module> readFile2();
void listmoduleRecord(vector<Module>);
bool moduleName (Module m1, Module m2);
vector<Student> getStudentByModule(vector<Student>,string);
bool isDuplicateStudentRecord(vector<Student>, Student);
//gloval variable
vector<Student> duplicates;
int main() {
int choice;
vector<Student> students;//list of student
vector<Module> modules;
vector<Student> list;
do {
printMenu();
cin >> choice;
switch(choice) {
case 1:
cout << "Read Student file ... " << endl;
students =readFile();
cout<<"Number of records read: " <<students.size() <<endl;
break;
case 2:
liststudentRecord(students);
break;
case 3:
cout << "Read Module file ... " << endl;
modules =readFile2();
cout<<"Number of records read: " <<modules.size() <<endl;
break;
case 4:
listmoduleRecord(modules);
break;
case 5:
liststudentRecord(duplicates);
break;
case 6:
cout << "Enter Module Code: ";
string code;
cin >> code;
list = getStudentByModule(students, code);
for (int i=0; i < list.size(); i++ ){
Student s = list.at(i);
cout << s.toString() << endl;
}
cout<<"List Student by Module Code"<<endl;
break;
case 7:
//http://www.cplusplus.com/reference/algorithm/sort/
//sort(students.begin(), students.end(), test1finalScoreAscending);
sort(students.begin(), students.end(),test1finalScoreAscending); //finalScoreAcending
break;
case 8:
break;
case 9: cout << "Exiting program... " << endl; break;
default:
cout << "Invalid option specified. Please try again" << endl;
}
} while(choice != 9);
return 0;
}
void printMenu() {
cout << "Menu" << endl;
cout << "----" << endl;
cout << "[1] Read student file" << endl;
cout << "[2] List student records" << endl;
cout << "[3] Read module file" << endl;
cout << "[4] List module records" << endl;
cout << "[5] List Duplicate Record" << endl;
cout << "[6] Display Student by Module" << endl;
cout << "[7] Sort by Final Score" <<endl;
cout << "[8] Write to file" << endl;
cout << "[9] Exit" << endl;
cout << "Choice: ";
}
vector<Student>readFile(){
vector<Student>students;
string filename;
ifstream inputFile;
cout << "Enter filename: ";
cin >> filename;
inputFile.open(filename, ios::in);//open file, read only
if(inputFile.is_open()){
while (inputFile.good()){
string line;
getline(inputFile, line);
Student s; //create a new student
//extract id
int i = line.find(",");
string id = trim(line.substr(0, i));// extract id
s.setId(id); // set student id
line = line.substr(i+1);// remove id form line
/*if(isvalidStudentid(id)){
string s = id.substr(0,1);
const char* s = id.substr(1,7);
}*/
//extract name
i = line.find(",");
string name = trim(line.substr(0, i)); // extract name
s.setName(name); //set student name
line = line.substr(i+1); //remove name from line
//extract classcode
i = line.find(",");
string classcode = trim(line.substr(0, i));
s.setClasscode(classcode);
line = line.substr(i+1);
if(isValidClasscode(classcode)){
string module = classcode.substr(0,6);
s.setModule(module);
string status = classcode.substr(7,9);
char *ft ="FT";
if(status.compare(ft)==0){
s.setFulltime(true);
}else{
s.setFulltime(false);
}
string classnumber = classcode.substr(9,11);
s.setClassnumber(classnumber);
}
//to use a for-loop for attendance
for (int j =0; j < 10 ; j++){
i = line.find(",");
string attendance = trim(line.substr(0, i));
s.setAttendance(j, attendance);
line = line.substr(i+1);
}
//to extreact test1
i = line.find(",");
int test1 = stoi(line.substr(0, i));
s.setTest1(test1);
line = line.substr(i+1);
//to extreact test2
i = line.find(",");
int test2 = stoi(line.substr(0, i));
s.setTest2(test2);
line = line.substr(i+1);
//to extreact tutorial
i = line.find(",");
int tutorial = stoi(line.substr(0, i));
s.setTutorial(tutorial);
line = line.substr(i+1);
//to extreact exam
i = line.find(",");
int exam = stoi(line.substr(0, i));
s.setExam(exam);
line = line.substr(i+1);
//need to do validationfirst
//to only add the valid student
if(isDuplicateStudentRecord(students, s) == false){
students.push_back(s); //add student to list
} else {
duplicates.push_back(s);
}
//cout<< line << endl;
}
inputFile.close();
}else{
cout << "Invalid file" << endl;
}
return students;
}
void liststudentRecord(vector<Student> list){
int numberStudents = list.size();
if (numberStudents > 0){
for (int i = 0; i < numberStudents; i++){
Student s = list.at(i);
cout << s.toString() << endl;
}
}else{
cout << "Empty list" <<endl;
}
}
bool test1Ascending(Student s1, Student s2){
return s1.getTest1() < s2.getTest1();
}
bool test1Descending(Student s1, Student s2){
return s1.getTest1() < s2.getTest1();
}
bool finalScoreAscending(Student s1, Student s2){
return s1.getFinalScore() < s2.getFinalScore();
}
bool isvalidStudentid(string s){
int i;
if(s.length() !=8){
return false;} //first check th length is 8
if (s.at(i) != 'S') {
return false;} //start with s
for (i =1 ; i<8; i++){ //7 digit
if(isdigit(s.at(i))==0){
return false;
}
}
return false;
}
bool isValidClasscode(string s){
int i;
if(s.length() !=11){
return false;} //first check th length is 8
for (i =0 ; i<3; i++){ // first 3 char are letters
if(isalpha(s.at(i))==0){
return false;}
}
for (i =3 ; i<6; i++){ //next 3 char are number
if(isdigit(s.at(i)) == 0){
return false;}
}
if (s.at(6) != '-') {
return false;} //has a hyphen
if (s.at(7) != 'F' && s.at(7) != 'P') {
return false;}
if (s.at(8) != 'T' ) {
return false;} // T
if (isdigit(s.at(9)) == 0 || isdigit(s.at(10)) == 0){
return false;}
return false;
}
vector<Module> readFile2(){
vector<Module>modules;
string filename;
ifstream inputFile;
cout << "Enter filename: ";
cin >> filename;
inputFile.open(filename, ios::in);//open file, read only
if(inputFile.is_open()){
while (inputFile.good()){
string line;
getline(inputFile, line);
Module m; //create a new student
//extract name
int i = line.find(",");
string modulecode = trim(line.substr(0, i));// extract id
m.setModulecode(modulecode); // set student id
//cout << id<< endl;
line = line.substr(i+1);// remove id form line
//cout << line << endl;
//extract id
i = line.find(",");
string modulename = trim(line.substr(0, i)); // extract name
m.setModulename(modulename); //set student name
line = line.substr(i+1); //remove name from line
//to extreact test1
i = line.find(",");
int test1 = stoi(line.substr(0, i));
m.setTest1(test1);
line = line.substr(i+1);
//to extreact test2
i = line.find(",");
int test2 = stoi(line.substr(0, i));
m.setTest2(test2);
line = line.substr(i+1);
//to extreact tutorial
i = line.find(",");
int tutorial = stoi(line.substr(0, i));
m.setTutorial(tutorial);
line = line.substr(i+1);
//to extreact exam
i = line.find(",");
int exam = stoi(line.substr(0, i));
m.setExam(exam);
line = line.substr(i+1);
modules.push_back(m); //add student to list
//cout<< line << endl;
}
inputFile.close();
}else{
cout << "Invalid file" << endl;
}
return modules;
}
void listmoduleRecord(vector<Module> list){
int numberModules = list.size();
if (numberModules > 0){
for (int i = 0; i < list.size(); i++){
Module m = list.at(i);
cout << m.toString() << endl;
}
}else{
cout << "Empty list" <<endl;
}
}
vector<Student> getStudentByModule(vector<Student> students,string code){
vector<Student> list;
for (int i=0; i< students.size(); i++){
Student s = students.at(i);
if (code.compare(current_module) == 0){
list.push_back(s);
}
}
return list;
}
bool isDuplicateStudentRecord(vector<Student> student, Student s){
string id = student.getId();
string name = student.getName();
string module = student.getModule();
for(int i=0; i< student.size(); i++){
Student s = student.at(i);
string current_id = s.getId();
string current_name = s.getName();
string current_module = s.getModule();
if(id.compare)(current_id) == 0 &&
name.compare(current_name) == 0 &&
(module.compare(current_module) == 0);{
return true;
}
}
return false;
}
//http://stackoverflow.com/a/6500499/3839235
string trim(string s){
s.erase(0, s.find_first_not_of(' ')); //prefixing spaces
s.erase(s.find_last_not_of(' ')+1); //surfixing spaces
return s;
}
Module.cpp
#include "Module.h"
#include <sstream>
using namespace std;
Module::Module(void){
}
string Module:: getModulecode(){
return modulecode;
}
void Module::setModulecode(string modulecode){
this->modulecode = modulecode;
}
string Module:: getModulename(){
return modulename;
}
void Module:: setModulename(string modulename){
this->modulename = modulename;
}
int Module:: getTest1(){
return test1;
}
void Module:: setTest1(int value1){
test1 = value1;
}
int Module:: getTest2(){
return test2;
}
void Module:: setTest2(int value2){
test2 = value2;
}
int Module:: getTutorial(){
return tutorial;
}
void Module:: setTutorial(int value3){
tutorial = value3;
}
int Module:: getExam(){
return exam;
}
void Module:: setExam(int value4){
exam = value4;
}
string Module::toString(){
stringstream ss;
ss<<"Module Code: " << modulecode<< "-"<< modulename <<endl;
ss << "Test 1: " << getTest1Percentage() << "%" << endl;
ss << "Test 2: " << getTest2Percentage() << "%" << endl;
ss << "Tutorial: " << getTutorialPercentage() << "%" << endl;
ss << "Exam: " << getExamPercentage() << "%" << endl;
//ss<< "Score percentage: " << getScorePercentage() << "%"<< endl;
ss<< "Final score: " << getFinalScore() << "%" <<endl;
return ss.str();
}
int Module::getTest1Percentage(){
int result;
result = (getTest1() * 100) / 100;
return result;
}
int Module::getTest2Percentage(){
int result;
result = (getTest2() * 100) / 100;
return result;
}
int Module::getTutorialPercentage(){
int result;
result = (getTutorial() * 100) / 100;
return result;
}
int Module::getExamPercentage(){
int result;
result = (getExam() * 100) / 100;
return result;
}
int Module::getFinalScore(){
int final = getTest1Percentage()+getTest2Percentage()+getTutorialPercentage()+getExamPercentage();
return final;
}
/*int Module::getFinalScore(){
int final = test1+test2+tutorial+exam;
return final;
}*/
Student.cpp
#include "Student.h"
#include <sstream>
using namespace std;
Student::Student(void){
}
string Student:: getId(){
return id;
}
void Student:: setId(string newid){
id = newid;
}
string Student:: getName(){
return name;
}
void Student:: setName(string name){
this->name = name;
}
string Student:: getClasscode(){
return classcode;
}
void Student::setClasscode(string classcode){
this->classcode = classcode;
}
string Student:: getAttendance(int i){
return attendance[i];
}
void Student:: setAttendance(int i, string value){
attendance[i] = value;
}
int Student:: getTest1(){
return test1;
}
void Student:: setTest1(int value1){
test1 = value1;
}
int Student:: getTest2(){
return test2;
}
void Student:: setTest2(int value2){
test2 = value2;
}
int Student:: getTutorial(){
return tutorial;
}
void Student:: setTutorial(int value3){
tutorial = value3;
}
int Student:: getExam(){
return exam;
}
void Student:: setExam(int value4){
exam = value4;
}
string Student::toString(){
stringstream ss;
ss << name << "(" <<id << ")" << endl;
ss << classcode << endl;
for(int i=0; i<10; i++){
ss << getAttendance(i) << " ";
}
ss << endl;
ss << "Test 1: " << test1 << endl;
ss << "Test 2: " << test2 << endl;
ss << "Tutorial: " << tutorial << endl;
ss << "Exam: " << exam << endl;
ss<< "Attendance percentage: " << getAttendancePercentage() << "%"<< endl;
ss<< "Final score: " << getFinalScore() <<endl;
return ss.str();
}
double Student::getAttendancePercentage(){
int n =0 ; // n will be the total number of "yes"
for (int i=1; i<10; i++){
string s = getAttendance(i);
char*yes = "yes";
if(s.compare(yes)== 0){
n++;
}
}
double percentage = n/10.0 * 100; //avoud interger division
return percentage;
}
int Student::getFinalScore(){
int final = test1+test2+tutorial+exam;
return final;
}
/*string Student::getModule() { return module; }
void Student::setModule(string m) { module = m;}
bool Student::getFulltime() { return fulltime; }
void Student::setFulltime(bool v) { fulltime = v;}
string Student::getClassnumber() { return classnumber; }
void Student::setClassnumber(string v) { classnumber = v;} */
string Student:: getModule(){
return module;
}
void Student:: setModule(string m){
module =m;
}
bool Student:: getFulltime(){
return fulltime;
}
void Student:: setFulltime(bool v){
fulltime = v;
}
string Student:: getClassnumber(){
return classnumber;
}
void Student:: setClassnumber(string c){
classnumber = c;
}
module.h中
#ifndef MODULE_H
#define MODULE_H
#include <string>
using namespace std;
class Module {
public:
Module();
string getModulecode();
void setModulecode(string);
string getModulename();
void setModulename(string);
int getTest1();
void setTest1(int);
int getTest2();
void setTest2(int);
int getTutorial();
void setTutorial(int);
int getExam();
void setExam(int);
string toString(); //to displayed info
int getTest1Percentage();
int getTest2Percentage();
int getTutorialPercentage();
int getExamPercentage();
int getFinalScore();
private:
string modulecode;
string modulename;
int test1;
int test2;
int tutorial;
int exam;
};
#endif //MODULE_H
Student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
using namespace std;
class Student {
//methods
public:
Student();
string getId();
string getName();
string getClasscode();
string getAttendance(int);
int getTest1();
int getTest2();
int getTutorial();
int getExam();
void setId(string);
void setName(string);
void setClasscode(string);
void setAttendance(int, string);
void setTest1(int);
void setTest2(int);
void setTutorial(int);
void setExam(int);
string toString(); //to displayed info
double getAttendancePercentage();
int getFinalScore();
string getModule();
void setModule(string);
bool getFulltime();
void setFulltime(bool);
string getClassnumber();
void setClassnumber(string);
//to create the get and set methods for all the attributes
//attribute
private:
string id;
string name;
string classcode;
string module;
bool fulltime;
string classnumber;
string attendance[10];
int test1;
int test2;
int tutorial;
int exam;
};
#endif //STUDENT_Hs
答案 0 :(得分:2)
从您提到的第一个错误看来,您的编译器抱怨您创建的字符串变量&#39; code&#39;在案例内部6.尝试将变量的创建移动到上面创建其他变量的位置。这应该可以解决您遇到的第一个错误。
至于第二个和第三个错误,它告诉你功能&#39; getId&#39;和&#39; getModule&#39;是你的&#39;模块的功能&#39; class,意思是你只能在&#39;模块的实例上调用它们。类。但是,您试图在学生对象的矢量上调用它们。
答案 1 :(得分:1)
在switch
语句中声明变量是一个坏主意:
switch(i) {
case 1:
int foo = 42;
doSomething(foo);
break;
case 2:
// aargh `foo` is in scope but uninitialised if we jump to here
...
}
要解决此问题,请将int foo
置于switch
语句之外,或将其放在switch
语句中的本地范围内:
switch(i) {
case 1:
{
int foo = 42;
doSomething(foo);
} // foo is destroyed
break;
case 2:
// there is no foo, there is no problem
...
}
通过更改,我已经通过clang格式和在线Clang编译器放置代码,因为Clang有可爱的错误消息。这就是Clang所说的:
prog.cc:69:27: warning: comparison of integers of different signs: 'int' and 'size_type' (aka 'unsigned long') [-Wsign-compare]
for (int i = 0; i < list.size(); i++) {
~ ^ ~~~~~~~~~~~
prog.cc:151:20: warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings]
char *ft = "FT";
^
prog.cc:243:12: warning: variable 'i' is uninitialized when used here [-Wuninitialized]
if (s.at(i) != 'S') {
^
prog.cc:237:8: note: initialize the variable 'i' to silence this warning
int i;
^
= 0
prog.cc:364:23: warning: comparison of integers of different signs: 'int' and 'size_type' (aka 'unsigned long') [-Wsign-compare]
for (int i = 0; i < list.size(); i++) {
~ ^ ~~~~~~~~~~~
prog.cc:377:22: error: use of undeclared identifier 'current_module'
if (code.compare(current_module) == 0) {
^
prog.cc:375:21: warning: comparison of integers of different signs: 'int' and 'size_type' (aka 'unsigned long') [-Wsign-compare]
for (int i = 0; i < students.size(); i++) {
~ ^ ~~~~~~~~~~~~~~~
prog.cc:385:23: error: no member named 'getId' in 'std::__1::vector<Student, std::__1::allocator<Student> >'
string id = student.getId();
~~~~~~~ ^
prog.cc:386:25: error: no member named 'getName' in 'std::__1::vector<Student, std::__1::allocator<Student> >'
string name = student.getName();
~~~~~~~ ^
prog.cc:387:27: error: no member named 'getModule' in 'std::__1::vector<Student, std::__1::allocator<Student> >'
string module = student.getModule();
~~~~~~~ ^
prog.cc:393:12: error: reference to non-static member function must be called
if (id.compare)
~~~^~~~~~~
( snipped: a lot of suggestions for what you might have meant instead )
prog.cc:394:20: error: invalid operands to binary expression ('string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') and 'int')
(current_id) == 0 && name.compare(current_name) == 0 &&
~~~~~~~~~~~~ ^ ~
prog.cc:384:64: warning: unused parameter 's' [-Wunused-parameter]
bool isDuplicateStudentRecord(vector<Student> student, Student s) {
^
prog.cc:388:21: warning: comparison of integers of different signs: 'int' and 'size_type' (aka 'unsigned long') [-Wsign-compare]
for (int i = 0; i < student.size(); i++) {
~ ^ ~~~~~~~~~~~~~~
7 warnings and 6 errors generated.
其中一些是次要的(但值得修复,例如for(size_t i = 0...
而不是int
),但标记为“错误”的是更重要的是。将编译器设置为对所有内容发出警告,然后使所有警告都消失,这通常是一种很好的做法。
你可以在这里的在线Clang编译器中看到代码(switch
中的额外大括号和LLVM样式的所有clang格式):http://melpon.org/wandbox/permlink/qLnE80Hs6FJWl9Fy
出现student.getID()
错误,因为在此函数中:
bool isDuplicateStudentRecord(vector<Student> student, Student s) {
string id = student.getId();
string name = student.getName();
string module = student.getModule();
...
您试图getID()
vector<Student>
而不是Student
。您的意思是string id = s.getID();
吗?
答案 2 :(得分:1)
更改后。
case 6:{
cout << "Enter Module Code: ";
string code;
cin >> code;
list = getStudentByModule(students, code);
for (int i=0; i < list.size(); i++ ){
Student s = list.at(i);
cout << s.toString() << endl;
}
cout<<"List Student by Module Code"<<endl;
break;
}
vector<Student> getStudentByModule(vector<Student> students,string code){
vector<Student> list;
for (int i=0; i< students.size(); i++){
Student s = students.at(i);
if (code.compare(current_module) == 0){
list.push_back(s);
}
}
return list;
}
重复
bool isDuplicateStudentRecord(vector<Student> student, Student s){
string id = s.getId();
string name = s.getName();
string module = s.getModule();
for(int i=0; i< student.size(); i++){
Student s = student.at(i);
string current_id = s.getId();
string current_name = s.getName();
string current_module = s.getModule();
if(id.compare)(current_id) == 0 &&
name.compare(current_name) == 0 &&
(module.compare(current_module) == 0);{
return true;
}
错误显示如下。
1&gt; c:\ users \ cry83 \ documents \ visual studio 2010 \ projects \ partb \ partb \ partb.cpp(378):错误C2065:&#39; current_module&#39; :未声明的标识符
1&gt; c:\ users \ cry83 \ documents \ visual studio 2010 \ projects \ partb \ partb \ partb.cpp(391):警告C4018:&#39;&lt;&#39; :签名/未签名不匹配
1&gt; c:\ users \ cry83 \ documents \ visual studio 2010 \ projects \ partb \ partb \ partb.cpp(396):错误C3867:&#39; std :: basic_string&lt; _Elem,_Traits,_Ax&gt;: :比较&#39;:函数调用缺少参数列表;使用&#39;&amp; std :: basic_string&lt; _Elem,_Traits,_Ax&gt; :: compare&#39;使用[_Elem = char,_Traits = std :: char_traits,_Ax = std :: allocator]
创建指向成员的指针1&gt; partb.cpp(396):错误C2678:二进制&#39; ==&#39; :找不到哪个运算符采用了类型为&#39; std :: string&#39;的左手操作数。 (或者没有可接受的转换)
1&GT; c:\ program files(x86)\ microsoft visual studio 10.0 \ vc \ include \ exception(470):可能是&#39; bool std :: operator ==(const std :: _ Exception_ptr&amp;,const std :: _ Exception_ptr &安培;)&#39;
1&GT; c:\ program files(x86)\ microsoft visual studio 10.0 \ vc \ include \ exception(475):或&#39; bool std :: operator ==(std :: _ Null_type,const std :: _ Exception_ptr&amp;)& #39;
1&GT; c:\ program files(x86)\ microsoft visual studio 10.0 \ vc \ include \ exception(481):或&#39; bool std :: operator ==(const std :: _ Exception_ptr&amp;,std :: _ Null_type)& #39;
1&GT; c:\ program files(x86)\ microsoft visual studio 10.0 \ vc \ include \ system_error(408):或者&#39; bool std :: operator ==(const std :: error_code&amp;,const std :: error_condition&amp; ;)&#39;
1&GT; c:\ program files(x86)\ microsoft visual studio 10.0 \ vc \ include \ system_error(416):或&#39; bool std :: operator ==(const std :: error_condition&amp;,const std :: error_code&amp; ;)&#39;
1&GT;尝试匹配参数列表&#39;(std :: string,int)&#39;