assigning a digit from a string to a variable

hi im trying to assign the first and second entries from a string to other variables

1
2
3
4
5
6
7
8
9
10
string answer;

cout << "enter a string";
cin >> answer;
	if (isalpha(answer[0]))
		ansCharacter=answer[0];
	if (isdigit(answer[1]))
		ansDigit= answer[1];

cout << ansCharacter<<ansDigit<<endl;


this works for the first character but when i try it for the second digit instead of returning a digit it returns a 2 digit number.
Last edited on
It shouldn't work at all. '0' the character is not the same as 0 the number. To convert digits to the number they represent:
1
2
3
char dig='5';
int num=dig-'0';
cout << num << endl;

This prints the number 5.
sorry but that didnt really help me, answer is a string. How can i extract digit from a string?
int digit=answer[0]-'0';
Last edited on
Let's say you have a string called in and you need the ints var1 and var2.
Then:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string>
#include <sstream> // Needed to use stringstream.
...
...
string in, v1, v2;
getline(cin,in);
int end=-1, var1, var2;
if(in.find_first_not_of("1234567890, ")==std::string::npos){  //  First check on input.
        end=in.find(' ');
        if(!(in.find_first_of ("1234567890, ",end+1)==std::string::npos)){   // Second check on input.
                v1=in.substr(0,endComm);
                v2=in.substr(endComm+1,in.length());   // This makes sub-strings.
                stringstream(v1)>>var1;
                stringstream(v2)>>var2;}   // This does the actual work.
}

PS: You may need to replace the , (comma) in "1234567890, " with a . (dot) depending on your keyboard layout.
Although that's only needed if you change the code to work with floats.
Last edited on
Topic archived. No new replies allowed.