c++ - C++ 在使用 goto 语句第二次调用时忽略 getline()
问题描述
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
int main(){
ifstream f;
dc:
string loc;
cout<<"Enter file location: ";
getline(cin, loc);
ta:
try{
f.open(loc, ios::in);
if(!f.is_open())
throw runtime_error("File not found×");
else{
cout<<"File found✓"<<endl;
system("pause");
}
}catch(runtime_error e){
cout<<e.what()<<endl;
cout<<"Press 1 to try again\n 2 to change directory\nanyother key to cancel: ";
int x;
cin>>x;
if(x==1)
goto ta;
if(x==2)
goto dc;
}
cout<<"Thank you for trying.."<<endl;
f.close();
}
当我去标签dc
时,它没有排队。输出如下:
Enter file location: /storage/emulated/0/sample.txt
File not found×
Press 1 to try again
2 to change directory
anyother key to cancel: 2
Enter file location: File not found×
Press 1 to try again
2 to change directory
anyother key to cancel:
它必须再次获取文件名getline(cin, loc);
。请给我解决方案来解决这个问题
我在声明cin.ignore();
之前尝试过。goto dc;
它工作正常。但为什么?
请解释一下
解决方案
推荐阅读
- haskell - Haskell - map values of a list of tuples with another function
- linux - 如何在 bash 脚本的输入中给出由正则表达式表示的文件列表
- javascript - Socket.io 客户端套接字需要很长时间才能响应
- swift - UISearchController - 黑色矩形
- ruby-on-rails - Google OmniAuth for rails giving error "Missing required parameter: client_id"
- python - Get closest dictionary of data with Python
- javascript - Why can't I use Jinja in Javascript for a django site?
- smartystreets - 如何从 SmartyStreet API 获取国家、州、县和城市?
- c++ - 将数组写入位图c ++
- c# - 无法在 MVC 客户端中使用 JWT 进行身份验证