Carlos Martins
Carlos Martins

Reputation: 1

Convert string into int and char

How can I convert a string to int and char, with fixed number of positions, in C++? For example: I need to convert "A1920139" into char "A", int 192 (next three positions in the string), int 01 (following two positions), and int 39 (last two positions).

So far I have only managed to get each int by itself (1, 9, 2, 0, etc). I don't know how to get the char or define a fixed number of positions for the int. This is what I have managed to write:

string userstr;
int* myarray = new int[sizeof(userstr)];

userstr = "A1920139";

for (i = 1; i < userstr.size(); i++) {
   myarray[i] = userstr[i] - '0';
}

for (i = 1; i < userstr.size(); i++) {
   printf("Number %d: %d\n", i, myarray[i]);
}

Eventually I need to arrive at something like char="A", int_1=192, int_2=01, and int_3=39

Upvotes: 0

Views: 160

Answers (2)

Wyck
Wyck

Reputation: 11750

substr(pos, len) will get a substring starting at position pos of length len.

stoi will convert a string to an integer.

#include <string>
#include <iostream>

int main()
{
    std::string userstr = "A1920139";

    char c = userstr[0];
    int n1 = std::stoi(userstr.substr(1, 3));
    int n2 = std::stoi(userstr.substr(4, 2));
    int n3 = std::stoi(userstr.substr(6, 2));

    std::cout << c << ' ' << n1 << ' ' << n2 << ' ' << n3 << std::endl;
}

Upvotes: 1

rustyx
rustyx

Reputation: 85371

If I understand correctly, you want to parse a string at fixed positions, in that case you can use substr() and stoi() like this:

std::string userstr = "A1920139";
int myarray[3];

myarray[0] = std::stoi(userstr.substr(1, 3));
myarray[1] = std::stoi(userstr.substr(4, 2));
myarray[2] = std::stoi(userstr.substr(6, 2));

std::cout << "int_1=" << myarray[0] << ", int_2=" << myarray[1] << ", int_3=" << myarray[2] << std::endl;

Upvotes: 2

Related Questions