无法在 C++ 中的 switch 语句中打开文件
can't open a file in switch statement in c++
我的代码中有一个switch语句,如果用户选择1,他将被要求写入要写入的文件,如果他选择2;他会被要求写下要读取的文件名,但我得到了这个错误:
case标签跳过了"file_name"的初始化。
这是我的代码:
char FileName[100];
char f[100];
int choice;
bool x;
int idd,iddd;
string line;
cout<<"enter file name: "<<endl;
cin>>FileName;
ofstream products_out(FileName,ios::out);
products_out<<table.p<<" "<<table.n<<" "<<table.a<<" "<<table.b<<endl;
while(1){
cout<<"1-add product"<<endl;
cout<<"2-retreive product"<<endl;
cout<<"3-update name"<<endl;
cout<<"5-update cost"<<endl;
cout<<"6-update quantity"<<endl;
cout<<"4-exit"<<endl;
cin>>choice;
switch(choice){
case 1:
cout<<"enter id"<<endl;
cin>>id;
s.ID=id;
cout<<"enter name"<<endl;
cin>>name;
strcpy(s.name,name);
cout<<"enter cost"<<endl;
cin>>cost;
s.cost=cost;
cout<<"enter quantity"<<endl;
cin>>quantity;
s.quantity=quantity;
x=table.insert(s);
products_out<<s.ID<<" "<<s.name<<" "<<s.cost<<" "<<s.quantity<<endl;
cout<<"yes inserted"<<endl;
break;
case 2:
cout<<"enter id of product"<<endl;
cin>>idd;
cout<<"enter the file you want to open"<<endl;
cin>>f;
ifstream products_in(f,ios::in);
products_in.seekg(0, ios::beg);
getline(products_in, line);
if (line.find(id))
{
cout << endl << line;
}
break;
把你的箱子放在大括号里,如下所示:
case 2:
{
cout<<"enter id of product"<<endl;
cin>>idd;
cout<<"enter the file you want to open"<<endl;
cin>>f;
ifstream products_in(f,ios::in);
products_in.seekg(0, ios::beg);
getline(products_in, line);
if (line.find(id))
{
cout << endl << line;
}
}
开关用例只是标签,因此它们不会自己定义作用域,并且不能在其中声明变量。你必须放上大括号才能在switch标签中创建一个范围:
case 0:
{
std::ofstream os("myfile"); //Ok, note the braces
}
当然,因为案例只是标签,所以您不局限于只写案例范围。你可以玩这样棘手的游戏:
case 0:
{
std::ofstream ok_file("myfile"); //Ok, note the braces
case 1:
...
case 10:
}
default:
{
std::ofstream error_file("other file");
}
将每个案例的代码放入其自己的函数中。这将使switch
更容易阅读,并消除这种复杂性。
相关文章:
- 如何基于平台在制作文件中制作if语句?
- C++:更改 IF 语句中的输出文件
- C# 读取完全锁定的文本文件或读取 if 语句外部的输出
- 关闭文件流时出错,其存在取决于与 C++ 中的 .close() 语句相同的布尔值
- 通过解析文件构建逻辑语句
- 头文件中可以包含"using namespace"语句吗?
- 在 cpp 文件中格式化 printf 语句
- 文件读取内/外,两个读语句(逻辑?
- 使用和if/else语句输出到屏幕或文件
- 无法在 C++ 中的 switch 语句中打开文件
- 如何使用 C 编程在运行时在 SQL 语句中传递文件路径
- 在文件中搜索 printf 语句并替换为字符串值
- 包含语句:找不到 SDL/SDL.h 文件
- 包含所有必需 #include 语句的单个头文件
- 如果文件位于 if 语句中,为什么我无法写入文件?
- 找出.h文件之间的#define语句冲突
- #include 指令和"using"语句的顺序在C++头文件的开头是否重要?
- 从c++中的文件中的sql语句创建sqlite3db
- .cpp文件头部的静态语句未被调用
- 管理大量的#include语句和头文件