C ++要么是函数调用的循环问题

c++ either while loop issue for function call

本文关键字:循环 问题 函数调用      更新时间:2023-10-16

我下面的代码有一个问题,它可以工作,但是当我运行它时,它会显示

'代码 0: 代码 1:

我期待

"代码

0:"然后等待您的第一个输入,然后是"代码 1:"

这是我的代码:

using namespace std;

//function Definitions
int fStore();
void fPrint();

//global variable definitions
map <int, string> codeDB;               //map for inputStrings
string inputData;                       //store long string here
string status("EXIT");
int lineNum;
int main(){
    int choice;
    //menu here
    cin >> choice;
    switch(choice){
        case 1: fStore(); break;
        case 2: fPrint(); break;
        case 3: cout << "You chose third" << endl; break;
        default: cout << "Invalid Input" << endl;
    }
}
int fStore(){
    cout << "n----------Input your codes here-----------n" << endl;
    while (inputData.compare(status)){
        cout << "Code " << lineNum << ": ";
        getline(cin, inputData);
        codeDB.insert(pair<int, string>(lineNum, inputData));
        lineNum++;
    }
    inputData = "";
    main();
}

我很确定我只是在这里错过了一些东西。

问题是在operator >>变量choice中输入数据后,输入缓冲区包含与预先设置的键 ENTER 相对应的新行字符。接下来getline读取一个空字符串,直到遇到这个换行符。应使用成员函数忽略从缓冲区中删除此字符。例如

#include <limits>
//...
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), 'n' );

考虑到 main 可能不会在C++中递归调用。所以这个函数定义无效

int fStore(){
    cout << "n----------Input your codes here-----------n" << endl;
    while (inputData.compare(status)){
        cout << "Code " << lineNum << ": ";
        getline(cin, inputData);
        codeDB.insert(pair<int, string>(lineNum, inputData));
        lineNum++;
    }
    inputData = "";
    main();
}
此外,该函数

应具有一个返回语句,其中的表达式转换为 int 类型,因为该函数具有返回类型 int。

使用全局变量也是一个坏主意。例如,变量inputData仅用于函数fStore那么为什么它没有声明为函数的局部变量呢?