【发布时间】:2021-04-06 09:19:04
【问题描述】:
当我选择案例 4 或“显示视频详细信息”时,我在文本文件中搜索文本时遇到了困难。似乎 switch 语句中的 ifstream 不起作用。这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int choice;
//4
string line;
bool iffound = false;
string id1;
ifstream file("test.txt");
menu:
cout << "MENU" << endl
<< endl;
cout << "[1] NEW VIDEO" << endl;
cout << "[2] RENT A VIDEO" << endl;
cout << "[3] RETURN A VIDEO" << endl;
cout << "[4] SHOW VIDEO DETAILS" << endl;
cout << "[5] DISPLAY ALL VIDEOS" << endl;
cout << "[6] CHECK VIDEO AVAILABILITY" << endl;
cout << "[7] CUSTOMER'S MAINTENANCE" << endl;
cout << "[8] EXIT PROGRAM" << endl;
cout << "Choice: ";
cin >> choice;
switch (choice)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
{
file.open("test.txt");
cout << "<< SHOW VIDEO DETAILS >>" << endl
<< endl;
cout << "Enter Movie ID: ";
cin >> id1;
string idnum1 = "VIDEO ID: " + id1;
cout << idnum1 << endl;
while (file.good())
{
getline(file, line);
if (line == idnum1)
{
iffound = true;
for (int i = 0; i <= 3; i++)
{
getline(file, line);
cout << line << endl;
}
break;
}
}
file.close();
if (iffound != true)
{
cout << "Video not found!" << endl;
}
}
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
}
}
这是我的文本文件:
VIDEO ID : 1
MOVIE TITLE : IT
GENRE : HORROR
PRODUCTION : NEW LINE CINEMA
NUMBER OF COPIES: 0
it.jpg
VIDEO ID : 2
MOVIE TITLE : THE CALL
GENRE : HORROR
PRODUCTION : YONG FILM
NUMBER OF COPIES: 3
thecall.jpg
VIDEO ID : 3
MOVIE TITLE : I AM LEGEND
GENRE : HORROR
PRODUCTION : VILLAGE ROADSHOW
NUMBER OF COPIES: 6
iamlegend.jpg
当我输入一个有效的Id,例如1 时,它会输出“未找到视频”,而该 ID 显然存在。
但是当我尝试这段代码时,没有switch 语句,它可以工作:
int main()
{
ifstream file("test.txt");
string line;
bool find = false;
string id;
string img;
cout << "Enter movie ID: ";
cin >> id;
string idnum = "VIDEO ID : " + id;
cout << idnum << endl;
while (file.good())
{
getline(file, line);
if (line == idnum)
{
find = true;
for (int i = 0; i < 4; i++)
{
getline(file, line);
cout << line << endl;
}
getline(file, img);
cout << img;
}
}
file.close();
if (find != true)
{
cout << "Movie Not Found" << endl;
}
return 0;
}
但我需要在 switch 语句中运行它。
【问题讨论】:
-
string idnum1 = "VIDEO ID: " + id1;与string idnum = "VIDEO ID : " + id; -
@MikeVine 哦,我没注意到,但不幸的是,它仍然没有工作
-
如果第二个有效,为什么不使用它,即将解析代码复制到您的案例 4?
-
作为新用户,请拨打tour阅读How to Ask。特别是,您应该从代码中提取minimal reproducible example,这可能会为您提供自己解决问题所需的提示,特别是问题可能与 switch 语句无关。
标签: c++ switch-statement ifstream