0

Im trying to call different functions from keyboard but I've faced a few problems due to my lack of knowledge/experience with cin,istringstream etc.Here is my simplified code :

#include <iostream>
#include <sstream>

using namespace std;

int main(int argc,char **argv) {

    string line;
    do {
        getline(cin,line);
        istringstream iss(line);
        string word;
        iss >> word;
        if (word ==  "function") {
            int id;
            if (!(iss >> id)) {
                cout << "Not integer.Try again" << endl;
                continue;
            }
            cout << id << endl;
            iss >> word;
            cout << word << endl;
        }
        else cout << "No such function found.Try again!" << endl;
    } while (!cin.eof());

    cout << "Program Terminated" << endl;
    return 0;
}

The 2 problems I currently deal with are :

• Why after checking if I got an integer the do-while loop terminates when I type something that's not integer? (eg "function dw25")-Had to use continue; instead of break;.Thought break would exit the outer if-condition.

• How can I solve the problem that occurs when I type "function 25dwa" because I don't want to get id == 25 & word == dwa.

Alex R.
  • 314
  • 4
  • 12
  • 1
    http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – πάντα ῥεῖ Apr 10 '16 at 17:26
  • The reason why the do-while loop terminates is because you are using **break** .if (!(iss >> id)) {cout << "Not integer.Try again" << endl; **break;** } – Biruk Abebe Apr 10 '16 at 17:35
  • Yep figured it out myself and edited my post.Thanks tho.Still trying to figure a solution or a workaround for the 2nd question – Alex R. Apr 10 '16 at 17:37
  • Replace break with continue and read about parsers. – zdf Apr 10 '16 at 17:37

1 Answers1

1

I think you could use strtol to check if id is integer.

#include <iostream>
#include <sstream>
#include <stdlib.h>

using namespace std;

int main()
{
    string word, value;
    while ((cin >> word >> value)) {
        if (word == "function") {
            char* e;
            int id = (int) strtol(value.c_str(), &e, 10);
            if (*e) {
                cout << "Not integer.Try again" << endl;
                break;
            }
            cout << id << endl;
            if (!(cin >> word))
                break;

            cout << word << endl;
        } else {
            cout << "No such function found.Try again!" << endl;
        }
    }

    cout << "Program Terminated" << endl;
    return 0;
}
Like
  • 1,298
  • 12
  • 21