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

时间:2021-02-17 15:58:13

How do I convert a string into an array of integers? Can I use sstream, because atoi doesn't work?!

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

6 个解决方案

#1


As you said in the comments, you got a binary string and you want to convert it into integers. Use bitset for that:

正如您在评论中所说,您有一个二进制字符串,并且您希望将其转换为整数。使用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);
}

If you only have one binary number in that string str, you can get away with

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

unsigned long number = std::bitset<32>(str).to_ulong();

Converting that in C is also possible...

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

atoi can't parse binary numbers. But strtol can parse them if you tell it the right base.

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

#2


How exactly would you like the conversion to work? Do you simply want an array containing the ASCII value of each character in the array? (so "abc" becomes [97, 98, 99, 0])?

您希望转换工作到底如何?你只是想要一个包含数组中每个字符的ASCII值的数组吗? (所以“abc”变成[97,98,99,0])?

Or do you want to parse the string somehow? ("1, 2, 3" becomes an array [1, 2, 3])

或者你想以某种方式解析字符串? (“1,2,3”成为数组[1,2,3])

In the first case, in C++, I'd do something like this:

在第一种情况下,在C ++中,我会做这样的事情:

struct convert {
  int operator()(char c) {
    return static_cast<int>(c);
  }
};

std::string str = "hello world";
std::vector<int> result;
std::transform(str.begin(), str.end(), std::back_inserter(result), convert())

Of course you could use a raw array instead of the vector, but since the length of the string is probably going to be variable, and then arrays are just asking for trouble.

当然你可以使用原始数组而不是向量,但由于字符串的长度可能是变量,然后数组只是要求麻烦。

If this wasn't what you wanted, you might want to edit your question to be more specific.

如果这不是您想要的,您可能希望编辑您的问题以使其更具体。

#3


From what I understand, for input string "110013" would be converted to array {1,1,0,0,1,3}. Here is how to do it in C++:

据我所知,输入字符串“110013”将转换为数组{1,1,0,0,1,3}。以下是如何在C ++中执行此操作:

string a = "1110011000";
vector<int> v;
for(int i = 0 ; i < a.length() ; i++){
    v.push_back(a[i] -'0');
}

// Check the result
for(int i = 0 ; i < v.size() ; i++){
    cout << v[i] << endl;
}

#4


Quick string splitter routine:

快速字符串分割程序例程:

convert(string str, string delim, vector<int>& results)
{
  int next;
  char buf[20];
  while( (next= str.find_first_of(delim)) != str.npos ) {
    if (next> 0) 
      results.push_back(atoi(str.substr(0,next), buf, 10));
    str = str.substr(next+1);
  }
  if(str.length() > 0)
    results.push_back(atoi(str.substr(0,next), buf, 10));
}

You can use stringstream instead of atoi (which does work, on a single int at a time)

你可以使用stringstream而不是atoi(它确实可以在一个int上运行)

int i;
stringstream s (input_string)
s >> i;

If you combine my and jalf's code, you'll get something really good.

如果你结合我和jalf的代码,你会得到非常好的东西。

#5


Use the istream_iterator in conjunction with a string stream.

将istream_iterator与字符串流结合使用。

By Array I am assuming you really mean a std::vector as you don't know the number of integers at compile time. But the code can easily be modified to use an array rather than a vector.

通过数组我假设你真的是指一个std :: vector,因为你不知道编译时整数的数量。但是代码可以很容易地修改为使用数组而不是向量。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{
    std::string     data = "5 6 7 8 9";
    std::vector<int>    store;


    std::stringstream   dataStream(data);
    std::copy(std::istream_iterator<int>(dataStream),
              std::istream_iterator<int>(),
              std::back_inserter(store)
             );

    // This line just copies the store to the std::cout
    // To verify it worked.
    std::copy(store.begin(),
              store.end(),
              std::ostream_iterator<int>(std::cout,",")
             );
}

#6


Language: C

Header:

#include <stdlib.h>

Function Prototype:

long int strtol(const char *nptr, char **endptr, int base);

Example Usage:

strtol(nptr, (char **) NULL, 10);

#1


As you said in the comments, you got a binary string and you want to convert it into integers. Use bitset for that:

正如您在评论中所说,您有一个二进制字符串,并且您希望将其转换为整数。使用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);
}

If you only have one binary number in that string str, you can get away with

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

unsigned long number = std::bitset<32>(str).to_ulong();

Converting that in C is also possible...

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

atoi can't parse binary numbers. But strtol can parse them if you tell it the right base.

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

#2


How exactly would you like the conversion to work? Do you simply want an array containing the ASCII value of each character in the array? (so "abc" becomes [97, 98, 99, 0])?

您希望转换工作到底如何?你只是想要一个包含数组中每个字符的ASCII值的数组吗? (所以“abc”变成[97,98,99,0])?

Or do you want to parse the string somehow? ("1, 2, 3" becomes an array [1, 2, 3])

或者你想以某种方式解析字符串? (“1,2,3”成为数组[1,2,3])

In the first case, in C++, I'd do something like this:

在第一种情况下,在C ++中,我会做这样的事情:

struct convert {
  int operator()(char c) {
    return static_cast<int>(c);
  }
};

std::string str = "hello world";
std::vector<int> result;
std::transform(str.begin(), str.end(), std::back_inserter(result), convert())

Of course you could use a raw array instead of the vector, but since the length of the string is probably going to be variable, and then arrays are just asking for trouble.

当然你可以使用原始数组而不是向量,但由于字符串的长度可能是变量,然后数组只是要求麻烦。

If this wasn't what you wanted, you might want to edit your question to be more specific.

如果这不是您想要的,您可能希望编辑您的问题以使其更具体。

#3


From what I understand, for input string "110013" would be converted to array {1,1,0,0,1,3}. Here is how to do it in C++:

据我所知,输入字符串“110013”将转换为数组{1,1,0,0,1,3}。以下是如何在C ++中执行此操作:

string a = "1110011000";
vector<int> v;
for(int i = 0 ; i < a.length() ; i++){
    v.push_back(a[i] -'0');
}

// Check the result
for(int i = 0 ; i < v.size() ; i++){
    cout << v[i] << endl;
}

#4


Quick string splitter routine:

快速字符串分割程序例程:

convert(string str, string delim, vector<int>& results)
{
  int next;
  char buf[20];
  while( (next= str.find_first_of(delim)) != str.npos ) {
    if (next> 0) 
      results.push_back(atoi(str.substr(0,next), buf, 10));
    str = str.substr(next+1);
  }
  if(str.length() > 0)
    results.push_back(atoi(str.substr(0,next), buf, 10));
}

You can use stringstream instead of atoi (which does work, on a single int at a time)

你可以使用stringstream而不是atoi(它确实可以在一个int上运行)

int i;
stringstream s (input_string)
s >> i;

If you combine my and jalf's code, you'll get something really good.

如果你结合我和jalf的代码,你会得到非常好的东西。

#5


Use the istream_iterator in conjunction with a string stream.

将istream_iterator与字符串流结合使用。

By Array I am assuming you really mean a std::vector as you don't know the number of integers at compile time. But the code can easily be modified to use an array rather than a vector.

通过数组我假设你真的是指一个std :: vector,因为你不知道编译时整数的数量。但是代码可以很容易地修改为使用数组而不是向量。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{
    std::string     data = "5 6 7 8 9";
    std::vector<int>    store;


    std::stringstream   dataStream(data);
    std::copy(std::istream_iterator<int>(dataStream),
              std::istream_iterator<int>(),
              std::back_inserter(store)
             );

    // This line just copies the store to the std::cout
    // To verify it worked.
    std::copy(store.begin(),
              store.end(),
              std::ostream_iterator<int>(std::cout,",")
             );
}

#6


Language: C

Header:

#include <stdlib.h>

Function Prototype:

long int strtol(const char *nptr, char **endptr, int base);

Example Usage:

strtol(nptr, (char **) NULL, 10);