One of two input variants

Hi,
I need to convert digit into spelled-out(eg. "0 is zero") or spelled-out

to digit ("four is 4");

To do this i need to read in int or string. User can enter either digit or

spelled-out word. What i must to choose to read(string, int, or both)?

As i know string conversion to int is impossible. For this i need string vector

, but i'm confused about how to implement user's answer input.
Last edited on
Just read whatever the user inputs as a string and convert by hand. You're going to have to do it for the spelled out version anyway. Try something like:

1
2
3
4
std::string s;
std::cin >> s;
int n;
if(s == "0" || s == "zero") n = 0;
You will also have to recognize whether or not the input string contains only alphabetic characters or numeric characters to determine which conversion you want to use.

Use the std::find_if or std::count_if algorithm to determine which:

1
2
3
4
#include <algorithm>
#include <functional>
#include <iostream>
#include <string> 
1
2
3
4
5
6
7
8
9
10
11
12
cout << "Please enter your number: " << flush;
string s;
getline( cin, s );

if (count_if( s.begin(), s.end(), ptr_fun <int, int> ( isdigit ) ) == 0)
  {
  // perform your 'name' to 'digits' conversion here
  }
else
  {
  // perform your 'digits' to 'name' conversion here
  }

Hope this helps.
stringstream could also be handy here:

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
#include <sstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string input;
    int number;

    cout << "type \"quit\" to quit!" << endl;

    while (true)
    {
        getline(cin,input);
        if (input=="quit") break;

        stringstream buffer;
        buffer<<input;
        buffer>>number;

        if (!buffer || buffer.str().size()>1)
        {
            cout << "it's a string!" << endl;
            //string stuff here...
        }
        else
        {
            cout << "it's a digit!" << endl;
            //digit stuff here...
        }
    }

    return 0;
}
Topic archived. No new replies allowed.