Reputation: 469
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.
Upvotes: 0
Views: 762
Reputation: 1536
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;
}
Upvotes: 1