首页 > 解决方案 > 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✓&quot;<<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;它工作正常。但为什么?

请解释一下

标签: c++

解决方案


推荐阅读