[英]ifstream seems to not be working inside a switch statement
当我选择案例 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
,它输出'video not found',而 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 语句中运行它。
它与switch
无关,问题(除了已识别的连接字符串中缺少的空格)是您第二次重新打开已打开的文件(请注意,您没有在工作代码片段中这样做)。
发生的情况是 stream 缓冲区的错误 state 将设置为failbit
并且good()
将返回false
, while
循环内的所有内容都不会执行。
只需打开一次,您的代码就可以正常工作。
代替:
ifstream file("test.txt");
利用:
ifstream file;
或者只是删除:
file.open("test.txt");
当然,将空格添加到连接的字符串中:
string idnum1 = "VIDEO ID : " + id1;
^
我应该指出,您应该重新审视您对using namespace std;
检查这篇文章的原因和替代方法:
改变
string idnum1 = "VIDEO ID: " + id1;
至
string idnum1 = "VIDEO ID : " + id1;
添加一个空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.