Loop problem.

let's say user enter 1, the program will promt user to enter a txt file. whenever user input a txt file. my main menu will loop 2 times. how do i stop it from it looping 2 times. the function getinteger used to ignore other input other than integers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
 #include <iostream>
#include <fstream>
#include <cstdlib>>
#include <string>
using namespace std;

int getInteger()
{
    string str;

    do
    {
        getline(cin, str);
    }while (str.find_first_not_of( "-0123456789" ) != string::npos);

    return atoi(str.c_str());
}


void menu(){

    cout << "\nTest " << endl;
    cout << "Menu options :    " << endl;
    cout << "1. menu 1" << endl;
    cout << "2. menu2  " << endl;
    cout << "3. Exit   " << endl;
    //cin.ignore(100000, '\n');

}

void askuser(char *filename){
        ifstream in_stream;         // create object
        in_stream.open(filename);  //open file
        if (in_stream.fail() ){
        cout << " File failed to open!\n " ;
        cout << "\nEnter the file name : " ;
        cin >> filename;
        askuser(filename);
        }
        else{
        
        cout << " File avaialble " << endl;

}
}

int main(){
    int num;

    do{
    menu();
    cout << "\nPlease enter the number menu : ";
    num = getInteger();
    char filename[100];

    if(num == 1){
        //cin.ignore(100000, '\n');
        cout << "\nUser options : 1 " << endl;
        cout << "\nEnter the file name : " ;
        cin >> filename;
        askuser(filename);

        }

    }while( num < 3);
}
Last edited on
Hi,

Consider using a switch instead of the do loop. Make sure the switch has a default: case to catch bad input. Put it inside a while loop that is controlled by a bool Quit value. Provide a quit option in the menu.

There is a small example here:
http://www.cplusplus.com/forum/general/83524/#msg448244


Good Luck !!
You problem is the mix of >> and getline():

http://en.cppreference.com/w/cpp/string/basic_string/getline

(Read the Notes how to solve that)
Topic archived. No new replies allowed.