如何将 C++ 或 C 中的字符串转换为整数数组?

kas*_*sky -4 c c++

如何将字符串转换为整数数组?我可以使用sstream,因为atoi不起作用?!

Joh*_*itb 5

正如您在评论中所说,您得到了一个二进制字符串,并且想要将其转换为整数。使用 bitset 来实现:

std::istringstream is(str);
std::bitset<32> bits; // assuming each num is 32 bits long

while(is >> bits) {
    unsigned long number = bits.to_ulong();
    // now, do whatever you want with that long.
    v.push_back(number);
}
Run Code Online (Sandbox Code Playgroud)

如果该字符串中只有一个二进制数str,则可以逃脱

unsigned long number = std::bitset<32>(str).to_ulong();
Run Code Online (Sandbox Code Playgroud)

在 C 中转换也是可能的......

long value;
char const *c = str;
for(;;) {
    char * endp;
    value = strtol(c, &endp, 2);
    if(endp == c)
        break;

    /* huh, no vector in C. You gotta print it out maybe */
    printf("%d\n", value);
    c = endp;
}
Run Code Online (Sandbox Code Playgroud)

atoi无法解析二进制数。但strtol如果你告诉它正确的基础,就可以解析它们。