-1

My code below has one issue, it works but when I run it, it displays

'Code 0: Code 1:'

I'm expecting

'Code 0:' then waits for your first input and then next is 'Code 1:'

Here is my code:

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();
}

I'm pretty sure I'm just missing something here.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
eakdev
  • 101
  • 1
  • 10

1 Answers1

0

The problem is that after entering data in variable choice with operator >> the input buffer contains new line character that corresponds to preessed key ENTER. And next getline reads an empty string until encounteres this new line character. You should remove this character from the buffer using member function ignore. For example

#include <limits>

//...

std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

Take into account that main may not be called recursively in C++. So this function definition is invalid

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();
}

Moreover the function shall have a return statement with an expression converted to type int because the function has return type int.

Also it is a bad idea to use global variables. For example variable inputData is used only in function fStore so why was not it declared as a local variable of the function?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Wow, I asked for one question and learned several stuffs, c++ newbee here. Thank you I'll get back on you – eakdev Nov 21 '14 at 06:16
  • I added return 0 to main and changed int fStore to void fStore. Now when you say main() should not be called recursively do you mean main() only or it applies to all functions in general? – eakdev Nov 21 '14 at 06:24
  • @eakdev main shall not be called recursively in C++ though in C this is allowed. – Vlad from Moscow Nov 21 '14 at 08:42