c++ - How can I transform a user-defined string into an integer -
i ask user input string, let's input "abc" or"def"
then, want set integer = 1 if abc entered , 2 if def entered.
if else entered, want invalid value.
so @ end, i'll have integer assigned 1 or 2 if valid value entered.
#include<iostream> #include<string> #include<sstream> using namespace std; int main() { string input = ""; // how string/sentence spaces cout << "please enter valid sentence (with spaces):\n>"; getline(cin, input); cout << ".\n" << "you entered: " << input << endl << endl; int m if(input = abc) return 0; }
#include <iostream> #include <map> #include <string> #include <initializer_list> using namespace std; int main() { const std::map<std::string, int> lookuptable = { {"abc", 1}, {"def", 2} }; string input = ""; int m; while(true) { cout << "please enter valid sentence (with spaces):\n>"; getline(cin, input); std::map<std::string, int>::const_iterator = lookuptable.find(input); if (it != lookuptable.end()) { m = it->second; break; } } cout << "you entered: " << input << endl << endl; cout << "m = " << m << endl; }
second solution if want m const. assumes compiler supports lambda functions:
#include <iostream> #include <map> #include <string> #include <initializer_list> using namespace std; int main() { const std::map<std::string, int> lookuptable = { {"abc", 1}, {"def", 2} }; string input = ""; const int m = [&]() { while(true) { cout << "please enter valid sentence (with spaces):\n>"; getline(cin, input); std::map<std::string, int>::const_iterator = lookuptable.find(input); if (it != lookuptable.end()) return it->second; } }(); cout << "you entered: " << input << endl << endl; cout << "m = " << m << endl; }
if compiler not support above map initialization can use instead:
#include <iostream> #include <map> #include <string> using namespace std; std::map<std::string, int> initializemap() { std::map<std::string, int> map; map["abc"] = 1; map["def"] = 2; // add whatever else here return map; } int main() { const std::map<std::string, int> lookuptable = initializemap(); string input = ""; int m; while(true) { cout << "please enter valid sentence (with spaces):\n>"; getline(cin, input); std::map<std::string, int>::const_iterator = lookuptable.find(input); if (it != lookuptable.end()) { m = it->second; break; } } cout << "you entered: " << input << endl << endl; cout << "m = " << m << endl; }
Comments
Post a Comment