Where is the huge difference, which generates error C2360, in following two definitions?
switch (msg) {
case WM_PAINT:
HDC hdc;
hdc = BeginPaint(hWnd, &ps); // No error
break;
}
and
switch (msg) {
case WM_PAINT:
HDC hdc = BeginPaint(hWnd, &ps); // Error
break;
}
bobobobo
63.7k60 gold badges254 silver badges355 bronze badges
asked Nov 24, 2013 at 17:24
1
When a variable is declared in one case, the next case is technically still in the same scope so you could reference it there but if you hit that case without hitting this one first you would end up calling an uninitialised variable. This error prevents that.
All you need to do is either define it before the switch statement or use curly braces { } to make sure it goes out of scope before exiting a specific case.
switch (msg) {
case WM_PAINT:
{
HDC hdc;
hdc = BeginPaint(hWnd, &ps);
}
break;
}
answered Jul 2, 2019 at 5:38
LeninkumarLeninkumar
2943 silver badges3 bronze badges
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <conio.h> #include <fstream> using namespace std; struct employee { char name[10]; int number, hours; double rate, salary; }; int main() { employee w, a[30]; char namefile[10]; FILE* f, *ft; int size = sizeof(employee); int i, m; while (true) { cout << "save - 1 n"; cout << "open - 2 n"; cout << "add - 3 n"; cout << "task - 4 n"; cout << "writedown - 5 n"; cout << "exit - 0 n"; switch (_getch()) { case '1': system("cls"); cout << "namefile - "; cin >> namefile; f = fopen(namefile, "wb"); fclose(f); case '3': system("cls"); f = fopen(namefile, "ab"); while (true) { cout << "name - "; cin >> w.name; if (w.name[0] == '.') break; cout << "number - "; cin >> w.number; cout << "hours - "; cin >> w.hours; cout << "rate - "; cin >> w.rate; if (w.hours > 144) w.salary = ((w.hours - 144) * 2 + 144) * w.rate * 0.88; else w.salary = w.hours * w.rate * 0.88; fwrite(&w, size, 1, f); } fclose(f); break; case '2': system("cls"); cout << " namefile = "; cin >> namefile; f = fopen(namefile, "rb"); cout << " name number hours rate salary n"; while (fread(&w, size, 1, f)) printf(" %s %d %d %4.2lf %4.2lf n", w.name, w.number, w.hours, w.rate, w.salary); fclose(f); _getch(); break; case '4': system("cls"); // Сортировать файл f = fopen(namefile, "rb"); int n = 0; while (fread(&a[n], size, 1, f)) n++; fclose(f); for (i = 0; i < n - 1; i++) { m = i; for (int j = i + 1; j < n; j++) { auto r = a[m]; a[m] = a[i]; a[i] = r; } } f = fopen(namefile, "wb"); cout << "n The schedule of the airport" << endl; cout << " City Start Arrival" << endl; for (int k = 0; k < n; k++) { fwrite(&a[k], size, 1, f); printf(" %s %d %d %4.2lf %4.2lf n", w.name, w.number, w.hours, w.rate, w.salary); } fclose(f); _getch(); break; case '5': system("cls"); char nametxt[10]; cout << "Txt file name = "; cin >> nametxt; f = fopen(namefile, "rb"); ft = fopen(nametxt, "wt"); fprintf(ft, " name number hours rate salary n"); while (fread(&w, size, 1, f)) fprintf(ft, " %s %d %d %4.2lf %4.2lf n", w.name, w.number, w.hours, w.rate, w.salary); fclose(f); fclose(ft); break; case '0': return 0; } } } |
Я новичок в C ++, нет знаний по C ++. Я пишу код для студента и модуля. Требуется, чтобы модуль и ученик отображали итоговую оценку, а также дублирование. Когда я пишу случай 5 и случай 6, после компиляции он показывает ошибку ниже.
ошибка C2360: инициализация кода пропускается по метке case
см объявление «код»
ошибка C2361: инициализация «кода» пропускается по метке «по умолчанию»
см объявление «код»
ошибка C2039: ‘getId’: не является членом ‘std :: vector<_Ty>»
с [_Ty = Student]
ошибка C2039: «getModule»: не является членом «std :: vector»<_Ty>»
с [_Ty = Student]
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 8for (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
1
Решение
Из первой ошибки, о которой вы упомянули, кажется, что ваш компилятор жалуется на создание вашей строковой переменной ‘code’ внутри случая 6. Попробуйте переместить создание переменной туда, где вы сделали другие выше. Это должно исправить первую ошибку, которую вы получили.
Что касается второй и третьей ошибки, она говорит вам, что функции ‘getId’ и ‘getModule’ являются функциями из вашего класса ‘module’, что означает, что вы можете вызывать их только в экземплярах класса ‘module’. Тем не менее, вы пытаетесь вызвать их на вектор студенческих объектов.
2
Другие решения
Это плохая идея объявить переменную внутри 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 есть прекрасные сообщения об ошибках. Вот что должен сказать Кланг:
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
), но те, которые отмечены как «ошибка», более критичны. Как правило, рекомендуется настроить компилятор так, чтобы он предупреждал обо всем, а затем убрал все предупреждения.
Вы можете увидеть код (с дополнительными скобками в switch
и все в формате clang в стиле 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();
?
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> c: users cry83 documents visual studio 2010 projects partb partb partb.cpp (378): ошибка C2065: ‘current_module’: необъявленный идентификатор
1> c: users cry83 Documents visual studio 2010 projects partb partb partb.cpp (391): предупреждение C4018: ‘<‘: несоответствие со знаком / без знака
1> c: users cry83 documents visual studio 2010 projects partb partb partb.cpp (396): ошибка C3867: ‘std :: basic_string<_Elem, _Traits, _Ax> :: compare ‘: вызов функции отсутствует в списке аргументов; использовать&станд :: basic_string<_Elem, _Traits, _Ax> :: compare ‘для создания указателя на член с помощью [_Elem = char, _Traits = std :: char_traits, _Ax = std :: allocator]
1> partb.cpp (396): ошибка C2678: двоичный файл ‘==’: не найден оператор, который принимает левый операнд типа ‘std :: string’ (или нет приемлемого преобразования)
1> c: program files (x86) Microsoft Visual Studio 10.0 vc include exception (470): может быть ‘bool std :: operator == (const std :: _ Exception_ptr &, const std :: _ Exception_ptr &)»
1> c: программные файлы (x86) Microsoft Visual Studio 10.0 vc include exception (475): или ‘bool std :: operator == (std :: _ Null_type, const std :: _ Exception_ptr &)»
1> c: program files (x86) Microsoft Visual Studio 10.0 vc include exception (481): или ‘bool std :: operator == (const std :: _ Exception_ptr &, Станд :: _ Null_type)»
1> c: program files (x86) Microsoft Visual Studio 10.0 vc include system_error (408): или ‘bool std :: operator == (const std :: error_code &, const std :: error_condition &)»
1> c: program files (x86) Microsoft Visual Studio 10.0 vc include system_error (416): или ‘bool std :: operator == (const std :: error_condition) &, const std :: error_code &)»
1> при попытке сопоставить список аргументов ‘(std :: string, int)’
1
Keep getting error C2360 and C2361, it basically skips »nummer».
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
std::string numerals = «MDCLVX»;
int main()
{
int choice;
bool On = true;
while (On != false)
{
cout << endl;
cout << » 1 — Omvandla romersk siffra till arabisk siffra.n»;
cout << » 2 — Omvandla arabisk siffra till romersk siffra.n»;
cout << » 3 — Exit.n»;
cout << » Enter your choice and press return: «;
cin >> choice;
switch (choice)
{
case 1:
{
char romersk_nummer;
int nummer = 0;
cout << «Skriv in ett Romersk nummer (t.ex CCXIX) : «;
while (cin.get(romersk_nummer))
{
if (romersk_nummer == ‘M’)
nummer = nummer + 1000;
else if (romersk_nummer == ‘D’)
{
romersk_nummer = cin.peek();
if (numerals.find(romersk_nummer, 5) != std::string::npos)
{
nummer = nummer — 500;
continue;
}
else
{
nummer = nummer + 500;
continue;
}
}
else if (romersk_nummer == ‘C’)
{
romersk_nummer = cin.peek();
if (numerals.find(romersk_nummer, 4) != std::string::npos)
{
nummer = nummer — 100;
continue;
}
else
{
nummer = nummer + 100;
continue;
}
}
else if (romersk_nummer == ‘L’)
{
romersk_nummer = cin.peek();
if (numerals.find(romersk_nummer, 3) != std::string::npos)
{
nummer = nummer — 50;
continue;
}
else
{
nummer = nummer + 50;
continue;
}
}
else if (romersk_nummer == ‘X’)
{
romersk_nummer = cin.peek();
if (numerals.find(romersk_nummer, 2) != std::string::npos)
{
nummer = nummer — 10;
continue;
}
else
{
nummer = nummer + 10;
continue;
}
}
else if (romersk_nummer == ‘V’)
{
romersk_nummer = cin.peek();
if (numerals.find(romersk_nummer, 1) != std::string::npos)
{
nummer = nummer — 5;
continue;
}
else
{
nummer = nummer + 5;
continue;
}
}
else if (romersk_nummer == ‘I’)
{
romersk_nummer = cin.peek();
if (numerals.find(romersk_nummer) != std::string::npos)
{
nummer = nummer — 1;
continue;
}
else
{
nummer = nummer + 1;
continue;
}
}
else
{
cout << «Det du angett är ogiltigt»;
}
cout << nummer << endl;
}
break;
case 2:
int num;
cout << «Ange ett vanligt nummer: «;
cin >> num;
while (num > 0)
{
if (num >= 1000)
{
cout << «M»;
num -= 1000;
}
else if (num >= 900)
{
cout << «CM»;
num -= 900;
}
else if (num >= 500)
{
cout << «D»;
num -= 500;
}
else if (num >= 400)
{
cout << «CD»;
num -= 400;
}
else if (num >= 100)
{
cout << «C»;
num -= 100;
}
else if (num >= 90)
{
cout << «XC»;
num -= 90;
}
else if (num >= 50)
{
cout << «L»;
num -= 50;
}
else if (num >= 40)
{
cout << «XL»;
num -= 40;
}
else if (num >= 10)
{
cout << «X»;
num -= 10;
}
else if (num >= 9)
{
cout << «IX»;
num -= 9;
}
else if (num >= 5)
{
cout << «V»;
num -= 5;
}
else if (num >= 4)
{
cout << «IV»;
num -= 4;
}
else if (num >= 1)
{
cout << «I»;
num -= 1;
}
}
break;
case 3:
cout << «End of Program.n»;
On = false;
break;
default:
cout << «Not a Valid Choice. n»;
cout << «Choose again.n»;
cin >> choice;
break;
}
}
return 0;
}
}
It looks like you have at least one mismatched brace.
In future please use code tags when posting code.
In future try and help the beginners instead.
Hello Normal student,
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.
I found the second link to be the most help.
This is your code with comments and indenting to help you understand:
|
|
Not only does indenting help, but a quick comment on the closing brace } before it gets to far away really helps.
I tend to indent the case statement to help readability.
In the above code the indentation helps give a better idea of where the opening and closing {}s fall. The closing brace of case 1 is not where it should be and case 2 has no block to deal with defining a variable inside a case statement.
I have also found the when defining a variable in a case statement it works best when the individual case statement is defined with a block as in:
|
|
Once you straighten out the {}s the program will compile properly.
So far I have only worked on getting the program to compile. I have not tried to run it yet.
Note for the future: When posting an error message do not just put «C2360» copy and paste the whole error message. Some know that «C2360» is a VS error code, but not everyone does. Also there are times I can load up the code and it will not produce the same error message or fail with the same problem that the poster of the question is having, so the problem you have needs to be explained and what you get for an error message is what everyone needs to see.
It also helps to mention the operating system and IDE you are using.
Hope that helps,
Andy
Last edited on
I ran into a new error the other day that was non-obvious at first glance.
I had code structured something like (greatly simplified by way of example):
void MyFunction()
{
int a = GetValueOfA();
switch(a)
{
case 1:
int b = 2;
DoSomething(b);
break;
case 2:
int c = 3;
DoSomethingElse(c);
break;
}
}
This gave me an error on the second case «error C2360: initialization of ‘b’ is skipped by ‘case’ label.» *
What?!? This is one of those cases where the message is technically accurate after you understand what it says but utterly useless to explain what is going on or what the solution is at first glance. Or perhaps I’m slow. I stared at this for a bit before I comprehended what it was trying to tell me.
The root of the issue is that, while the case statements appear to be in their own scope, they aren’t. (I’m sure I knew this at some point, but the memory was overridden long ago. Or perhaps I have too many languages floating around in my head.) The scope for variables inside a switch statement is all the cases, not just the current case. Therefore, in the code above, variables b and c are available anywhere inside the switch statement. The error says b is defined, but may not be initialized properly, when a = 2.
All the solutions involve changing the scope of b and c. There are a couple immediately obvious solutions:
1) Put braces around the contents of the case statements to limit their scope.
void MyFunction()
{
int a = GetValueOfA();
switch(a)
{
case 1:
{
int b = 2;
DoSomething(b);
}
break;
case 2:
{
int c = 3;
DoSomethingElse(c);
}
break;
}
}
2) Put the contents of the case statements in their own functions, another way of limiting their scope.
void PerformCase1()
{
int b = 2;
DoSomething(b);
}
void PerformCase2()
{
int c = 3;
DoSomethingElse(c);
}
void MyFunction()
{
int a = GetValueOfA();
switch(a)
{
case 1:
PerformCase1();
break;
case 2:
PerformCase2();
break;
}
}
3) Move the declaration to before the switch statement and don’t do initialization/declaration on the same line.
void MyFunction()
{
int b, c;
int a = GetValueOfA();
switch(a)
{
case 1:
b = 2;
DoSomething(b);
break;
case 2:
c = 3;
DoSomethingElse(c);
break;
}
}
Another option would be to change the structure of the code such that the switch isn’t necessary. In general, this would be my favored solution although in this specific case of legacy code, that would have involved more work than the budget allowed.
* Actually my notes say I also got a second error on the switch stating «transfer of control bypasses initialization of variable b» but I could not reproduce this one. Perhaps I simplified too much. Or perhaps it was a different version of the compiler. Or perhaps different option settings. Or something else entirely.
error C2360: initialization of ‘i’ is skipped by ‘case’ label ?
My program has an error C2360: initialization of ‘i’ is skipped by ‘case’ label.
I don’t know why. Please help me out!
thks!!
the error occurs in Division case 3.
- //Claire’s Calculator
- #include
- #include
- double pow(double x, double y);
- main()
- <
- int choice, choicee;
- const double PI = 3.14159;
- float a, b, c;
- int n, m;
- double cy;
- double x, y;
- float x_to_the_y;
- double r;
- int re, q;
- do //
- <
- cout > choice; //get choice from the user
- if ((choice 8))
- <
- cout 8));
- switch(choice)
- <
- case 1: // Addition
- cout > a;
- cout > b;
- cout > a;
- cout > b;
- cout > a;
- cout > b;
- cout > choicee;
- >
- while ((choicee 3));
- switch(choicee)
- <
- case 1: //answer as a decimal
- cout > a;
- cout > b;
- cy = a / b;
- cout > n;
- cout > m;
- n = Denom;
- m = Num;
- for (i = n * m; i > 1; i—)
- <
- if ((n % i == 0) && (m % i == 0))
- <
- n /= i;
- m /= i;
- >
- >
- cout > a;
- cout > b;
- q = a / b;
- re = (int)a % (int)b;
- cout > a;
- cout > b;
- c = a * (b / 100);
- cout > x;
- cout > y;
- x_to_the_y = pow(x, y);
- cout > r;
- cout > a;
- double pow(double x, double y);
- cout > x;
- cout > y;
- x_to_the_y = pow(x, y);
- cout 4 24503
In case 2 try using:
int n, m, i;
n, m, i= 0;
instead of:
int n, m, i = 0;
not sure why it works this way.
Hi,
I think the error is coming becos the n,m declartion in case 2 is clashing with the declartion in the beginning of the program.
Enclose the case 2 inside curly brace like this
Hi,
I don’t know about the tags. I just started today.
The variables defined at the top of the program
are in scope for the duration of the entire program.
So declaring n and m again is not necessary in case 2.
You could declare i at the top of the program and then
you may not have a problem. If you want to keep i local,
it is correct to enclose the contents of the case in curly brackerts. That makes i a local variable for case 2.
It would not hurt to enclose each case in curly brackets and define your local variables for each case, if you would like to. Anyway, whatever is at the top is in scope to the end of the program. C++ allows you to declare
your variables near the applicable code, whereas C does not. So in your case, it would not hurt to take advantage of the capabilities of C++.
case 2: //answer as a fraction
int n, m, i = 0;
etc.
break;
case 3: //answer as a number with a remainder
// error C2360: initialization of ‘i’ is skipped by ‘case’ label
cout Expand | Select | Wrap | Line Numbers
- case 2: //answer as a fraction
- <
- int n, m, i = 0;
- >
- etc.
- break;
- case 3: //answer as a number with a remainder
- // error C2360: initialization of ‘i’ is skipped by ‘case’ label
- cout Message Cancel Changes
Post your reply
Sign in to post your reply or Sign up for a free account.
Источник
Error c2360 is skipped by case label
Please contact us if you have any trouble resetting your password.
case labels are just jump targets; there are no case «blocks» unless you write the block yourself. The reason the restriction you mention exists is best demonstrated with an example:
It is important to remember that a switch/case is just a fancy wrapper for a bunch of gotos and labels. For example, the code above is semantically equivalent to this:
[Edited by — Sharlin on March 24, 2006 6:04:31 PM]
Quote: Form MSDN
the variable is within scope until the end of the switch statement
So it could be used outside the particular case, without initialization, which is unsafe.
Although I’m surprised this (which is basically the same) goes away with a warning only:
Great explanation, thank you. So is it preferred to use blocks for local variables within a case block, or is it best to declare it outside the switch?
Depends on the solution.
Quote: Original post by deffer
Although I’m surprised this (which is basically the same) goes away with a warning only:
*** Source Snippet Removed ***
I guess they (VS team) don’t care much about safety of ‘goto’ users.
[grin]
Suspect that’ll turn into an error with a non-POD type. While bad mojo, I believe that example is technically valid — and hence inappropriate to cause a compile error on — unless you turn on whatever flag’s required for your compiler to treat warnings as errors :-).
Quote: Original post by MaulingMonkey
Suspect that’ll turn into an error with a non-POD type. While bad mojo, I believe that example is technically valid — and hence inappropriate to cause a compile error on — unless you turn on whatever flag’s required for your compiler to treat warnings as errors :-).
Now it’s semanticly the same, but with different treatment from the compiler (VS 7.1).
Quote: Original post by MaulingMonkey
Suspect that’ll turn into an error with a non-POD type. While bad mojo, I believe that example is technically valid — and hence inappropriate to cause a compile error on — unless you turn on whatever flag’s required for your compiler to treat warnings as errors :-).
*** Source Snippet Removed ***
Now it’s semanticly the same, but with different treatment from the compiler (VS 7.1).
In the code you typed, the destructor of B is called but the constructor is not. This is . not ideal.
Basically, always do this:
«Pretend» that code needs <>s after a case statement — even more, «pretend» that code needs
<
>break;
after a case statement.
(there are rare exceptions in which you can skip the break;, but . they should be used about as carefully as you would use a goto statement.)
Источник
Initialization skipped by case label
Hi everyone,
I have worked some more on my code and this time I am getting some error that I am not able to resolve. Please help me.
The error says: «initialization skipped by case label.» Please show me how to resolve this.
Here is the code. The error has a remark in red.
Really appreciate your help.
Thanks.
- 4 Contributors 5 Replies 4K Views 7 Hours Discussion Span Latest Post 14 Years Ago Latest Post by robgeek
You error is the fundamental language mistake. It is not possible
to declare any new variable or object in the scope of the switch statement that has outside scope. ifstream input(«help.txt»); is not allowed.
Additionally, you have already declared input at the top
[4 lines below main()].
To open an output stream it is output.open(«ParkingCharges.txt»,ios::out); NOT: ofstream.output(«Parking Charges.txt», ios::out); Because you are using a class name not an instance/object (ofstream is not an object) and you are using output which is not in the class or the public base classes.
All 5 Replies
You error is the fundamental language mistake. It is not possible
to declare any new variable or object in the scope of the switch statement that has outside scope. ifstream input(«help.txt»); is not allowed.
Additionally, you have already declared input at the top
[4 lines below main()].
If you want to try this
Further, you don’t actually use input and output, but define a NEW
instance of output in the function CarParking.
Источник
Compiler errors C2300 Through C2399
The articles in this section of the documentation explain a subset of the error messages that are generated by the compiler.
The Visual Studio compilers and build tools can report many kinds of errors and warnings. After an error or warning is found, the build tools may make assumptions about code intent and attempt to continue, so that more issues can be reported at the same time. If the tools make the wrong assumption, later errors or warnings may not apply to your project. When you correct issues in your project, always start with the first error or warning that’s reported, and rebuild often. One fix may make many subsequent errors go away.
To get help on a particular diagnostic message in Visual Studio, select it in the Output window and press the F1 key. Visual Studio opens the documentation page for that error, if one exists. You can also use the search tool at the top of the page to find articles about specific errors or warnings. Or, browse the list of errors and warnings by tool and type in the table of contents on this page.
Not every Visual Studio error or warning is documented. In many cases, the diagnostic message provides all of the information that’s available. If you landed on this page when you used F1 and you think the error or warning message needs additional explanation, let us know. You can use the feedback buttons on this page to raise a documentation issue on GitHub. If you think the error or warning is wrong, or you’ve found another problem with the toolset, report a product issue on the Developer Community site. You can also send feedback and enter bugs within the IDE. In Visual Studio, go to the menu bar and choose Help > Send Feedback > Report a Problem, or submit a suggestion by using Help > Send Feedback > Send a Suggestion.
You may find additional assistance for errors and warnings in Microsoft Learn Q&A forums. Or, search for the error or warning number on the Visual Studio C++ Developer Community site. You can also search Stack Overflow to find solutions.
For links to additional help and community resources, see Visual C++ Help and Community.
Источник
Error c2360 is skipped by case label
PRF |
|
||
Шустрый Профиль Репутация: нет Здравствуйте.. помогите пожалуйста, выдает почему то ошибку, вроде бы простой код, может я чего то не замечаю?
switch(key) /* ввод матрицы смежности */ break; |
выдает такую ошибку
error C2360: initialization of ‘first’ is skipped by ‘case’ label
error C2360: initialization of ‘matrix’ is skipped by ‘case’ label
помогите пожалуйста, вроде бы конструкция switch правильно использована..
vinter |
|
||
Explorer Профиль Репутация: 13
switch(key) /* ввод матрицы смежности */ break; |
Lazin |
|
||
Эксперт Профиль Репутация: 41
Это сообщение отредактировал(а) Lazin — 7.9.2008, 18:32 |
|||
|
PRF |
|
||
Шустрый Профиль Репутация: нет спасибо большое! раньше не знал этого момента((( Это сообщение отредактировал(а) PRF — 7.9.2008, 20:41 |
|||
|
Опытный
Профиль
Группа: Участник
Сообщений: 722
Регистрация: 30.3.2006
Репутация: 27
Всего: 32
UnrealMan |
|
||
Цитата(Lazin @ 7.9.2008, 19:31 ) |
между кейсами нельзя объявлять переменные |
Объявлять можно, инициализировать нельзя.
Это сообщение отредактировал(а) UnrealMan — 7.9.2008, 21:48
- Черновик стандарта C++ (за октябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика(4.4мб).
- Черновик стандарта C (за сентябрь 2005) можно скачать с этого сайта. Прямая ссылка на файл черновика (3.4мб).
- Прежде чем задать вопрос, прочтите это и/или это!
- Здесь хранится весь мировой запас ссылок на документы, связанные с C++ 🙂
- Не брезгуйте пользоваться тегами [code=cpp][/code].
- Пожалуйста, не просите написать за вас программы в этом разделе — для этого существует «Центр Помощи».
- C++ FAQ
Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Earnest Daevaorn
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) |
0 Пользователей: |
« Предыдущая тема | C/C++: Общие вопросы | Следующая тема » |
[ Время генерации скрипта: 0.1165 ] [ Использовано запросов: 21 ] [ GZIP включён ]
Источник
Adblock
detector