ifstream在选择菜单选项后不会打开文件

时间:2016-02-17 17:15:55

标签: c++ menu ifstream

所以我的主要代码是菜单。

BankAccount BA;
ifstream fin;
int UserAction = -1;

while (UserAction != 0) {
    cout << "menu here";
    cin >> UserAction;

    if (UserAction == 1)
        BA.getInstance(BA); //Input by keyboard. Works fine.
    if (UserAction == 2)
        BA.getInstance(BA, fin); //Input by file.
}

如果我选择选项#2,它将执行此代码:

void BankAccount::getInstance(BankAccount &BA, ifstream &fin) {
    string actN, fname, lname, InputFileName;
    double bal;

    fin.sync();
    cout << "Please enter input file path: ";
    getline(cin, InputFileName);
    if (fin.fail())
        cout << "failed";
    else {
        fin.open(InputFileName.c_str());
        BA.getInstance(BA, fin);
    }

    fin >> actN;
    fin >> lname;
    fin >> fname;
    fin >> bal;
    BA = BankAccount(actN, lname, fname, bal);
}

输入文件路径后,按Enter键,表示失败并将我踢到菜单。如果我把cin.sync();其中fin.sync是,它只是让我循环进入文件路径。请注意,它在菜单外部工作。我如何修复它以便正确打开文件路径而不会出现问题,以便处理信息?

1 个答案:

答案 0 :(得分:0)

1 - 将您的主要代码更改为 private async void ToSpeechButton_Click(object sender, RoutedEventArgs e) { MediaElement mediaElement = new MediaElement(); var tsc = new TaskCompletionSource<bool>(); mediaElement.MediaEnded += (o, f) => { tsc.TrySetResult(true); }; mediaElement.Play(); foreach (var item in ListBox.Items) { readText(item.ToString()); await tsc.Task; } } private async void readText(string mytext) { MediaElement mediaplayer = new MediaElement(); using (var speech = new SpeechSynthesizer()) { speech.Voice = SpeechSynthesizer.AllVoices.First(gender => gender.Gender == VoiceGender.Female); SpeechSynthesisStream stream = await speech.SynthesizeTextToStreamAsync(mytext); mediaplayer.SetSource(stream, stream.ContentType); mediaplayer.Play(); } } ,idk为什么人们在这种情况下选择while循环。

do-while

2 - fin.fails因为它未初始化,删除该行并且它将正常工作。尝试在do{ cout << "menu here"; cin >> UserAction; if (UserAction == 1) BA.getInstance(BA); //Input by keyboard. Works fine. if (UserAction == 2) BA.getInstance(BA, fin); //Input by file. } while(UserAction!=0);

之后使用fin.fail()