C ++要么是函数调用的循环问题
c++ either while loop issue for function call
我下面的代码有一个问题,它可以工作,但是当我运行它时,它会显示
'代码 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
那么为什么它没有声明为函数的局部变量呢?
相关文章:
- C++ 而循环问题 Codecademy 参考 [已解决]
- 按升序对数组进行排序嵌套循环问题
- 我在C 初学者中发现了无限的循环问题
- 冰雹序列C 函数需要计算序列的长度.无限循环问题
- QML&C++应用程序中的绑定循环问题
- 跳跃游戏中嵌套的循环问题
- 在文件中重复文本 - 循环问题
- C 代码循环问题
- C 如果/其他循环问题
- C 文件输入流循环问题
- C++ 中对象的循环问题
- 另一个C CIN循环问题
- C 华氏度到摄氏(反之亦然)循环问题
- C 完美的数字,带有嵌套循环问题
- 遇到 while 循环问题
- C++无限循环问题
- C++闹钟,循环问题
- 循环问题
- 简单的嵌套循环问题.*形状*
- C++数组循环问题仍然需要帮助