简体   繁体   English

将字符串转换为int和char

[英]Convert string into int and char

How can I convert a string to int and char, with fixed number of positions, in C++? 如何在C ++中将具有固定位数的字符串转换为int和char? 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). 例如:我需要将“ A1920139”转换为char“ A”,int 192(字符串中的后三个位置),int 01(后两个位置)和int 39(后两个位置)。

So far I have only managed to get each int by itself (1, 9, 2, 0, etc). 到目前为止,我仅设法单独获取每个int(1、9、2、0等)。 I don't know how to get the char or define a fixed number of positions for the int. 我不知道如何获取char或为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 最终,我需要得到类似char="A"int_1=192int_2=01int_3=39

If I understand correctly, you want to parse a string at fixed positions, in that case you can use substr() and stoi() like this: 如果我理解正确,则希望在固定位置解析字符串,在这种情况下,可以使用substr()stoi()这样:

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;

substr(pos, len) will get a substring starting at position pos of length len . substr(pos, len)将从长度为len位置pos开始获得子字符串。

stoi will convert a string to an integer. stoi将字符串转换为整数。

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM