[英]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.