跨越字符串的初始化并跳到标签情况
Crosses initialization of string and jump to label case
我正在尝试为程序做案例菜单。而且我总是会遇到交叉初始化的错误,我从未见过此错误。也许有人可以解释我的代码发生了什么问题。
#include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <fstream>
using namespace std;
#define N_CARS 1
struct car{
string model;
int year;
double price;
bool available;
}cars [N_CARS];
void menu();
void mainMenu();
void writeToFile(ofstream &outputFile , const car& p)
{
outputFile << p.model << " "
<< p.year << " "
<< p.price << " "
<< p.available<<"n";
}
int choice1 = 0;
int main(int argc, char** argv) {
menu();
return 0;
}
void menu() {
do {
mainMenu();
switch(choice1) {
case 1:
string mystr;
string mystr2;
string mystr3;
int n;
for (n=0; n<N_CARS; n++)
{
cout << "Enter title: ";
getline (cin,cars[n].model);
cout << "Enter year: ";
getline (cin,mystr);
stringstream(mystr) >> cars[n].year;
cout << "Enter price: ";
getline (cin,mystr2);
stringstream(mystr2) >> cars[n].price;
cout << "Choose availability: ";
getline (cin,mystr3);
stringstream(mystr3) >> cars[n].available;
}
ofstream outputFile;
outputFile.open("bla.txt", fstream::app);
for (n=0; n<N_CARS; n++)
writeToFile(outputFile, cars[n]);
outputFile.close();
break;
case 2:
break;
case 5:
break;
}
} while(choice1 != 5);
}
void mainMenu(void) {
cout << "Main Menun";
cout << "1 - Enter Carn";
cout << "5 - Quitn";
cout << "Please choose: ";
cin >> choice1;
}
错误:
In function 'void menu()':
[Error] jump to case label [-fpermissive]
[Error] crosses initialization of 'std::ofstream outputFile'
[Error] crosses initialization of 'std::string mystr3'
[Error] crosses initialization of 'std::string mystr2'
[Error] crosses initialization of 'std::string mystr'
case
标签确实很像可怕的 goto
标签;它们不构成新的范围。因此,switch
选择正确的case
标签要跳到或更糟的是,类似于goto
语句跳到标签。不允许跳跃穿越您的各种对象的初始化 - 正如错误消息所说的那样。
最干净的事情是将case 1:
和break; case 2:
之间的所有内容都切成新的函数称为enterCar
。
void enterCar() {
// code previously found between the case labels
}
// ...
switch(choice1) {
case 1: enterCar(); break;
case 2:
// ...
}
一个函数构成了一个新范围,可以在其中正确初始化本地对象。作为奖励,您正在将所有意大利面条代码留在您身后。
您必须在 case -blocks中包含变量定义,并带有示波器支架{}。
另一件事:忘记 #define 用于Comple Time常数,使用 constexpr :
constexpr size_t NumCars = 5;
还请注意 size_t :对于描述大小的变量和常数,例如阵列大小或索引,使用size_t。
此外,您包括 cstdlib 和 stdlib.h 。C-StandardLibrary的headerFiles始终应包含在C-Prefix和.h-sission中,因此踢出 stdlib.h 。无论如何您都不需要它。
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 函数中堆分配的效果与缺少堆分配的情况
- 在未初始化映射的情况下,将值插入到映射的映射中
- 是默认情况下分配给char数组常量的值
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 如何在不产生任何垃圾的情况下获得C中的像素
- 在已经使用Git的情况下减少编译时间
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 如何在没有信号的情况下从C++执行QML插槽
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 为什么在某些情况下不写入此文件?
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 在没有Xcode的情况下在Mac捆绑包中嵌入框架
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 为什么我们可以访问交换机其他情况下标签内的变量
- 跨越字符串的初始化并跳到标签情况
- 如何在不获取所有html的情况下获取QTextEdit的html标签?
- 如何在不使用两个标签的情况下对齐左侧的一些文本和右侧的一些文本