Ive recently been working on a C++ project where we are required to prompt the user for a string "command", take the first char from that string to decide exactly what command it is, and then take the remaining parts of that string and turn them into individual characters and integers... Im really unsure how to go about doing this... An example for a command would be something like:


With this, i would need to read the string and take the first character X(which could be a number of different letters, each corresponding to a different function to do) and then read each of the numbers into seperate integers such as:

w = 04
x = 03
y = 08
z = 12

And then the final character into a seperate char value...
I know how to read one specific character into a char but the thing that gets me from this is being able to read 2 positions into the string into one int.... Such as read the 0 and 4 in positions 1 and 2 into int x for example...

Im not sure what commands to use to do this at all... any pointers would help.


8 Years
Discussion Span
Last Post by tag234

I am not sure what you meen but if you have the string:

string str = "X04030812$"

and for example want to substring "04" you can do:


Where 1 is the startingposition in the string and 2 is the length.
Then you can convert it to int:

int Num = 0;

Num = atoi(str.substr(1,2));

I dont know if this helps.


thankyou! that will actually do exactly what i want


actually, when i try that i get this error:

\visual studio 2008\projects\prog.cpp(134) : error C2664: 'atoi' : cannot convert parameter 1 from 'std::basic_string<_Elem,_Traits,_Ax>' to 'const char *'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Ax=std::allocator<char>
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

and ive tried to fix it but still not able..


sorry my fault.. I think I forgot the .c_str();
Try and change to this instead:

int Num = 0;

Num = atoi(str.substr(1,2).c_str());
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.