String to Int conversion questions

Hello all,
I am new to c++. Please help with the following.
I have two strings, viz., "0, 1, 3, 2" and "-1, -1, 1, 1, 1, -1, -1, 1". I need to convert them to a vector of integers, viz., unsigint.at(0) = 0, ..., unsignint.at(3) = 2, and
signint.at(0) = -1, ..., signint.at(7) = 1.
Any ideas?
Thanks in advance.
Last edited on

If they're all single digits integers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <vector>
#include <iostream>
#include <cctype>

using namespace std;

int main()
{

  string originalString("0, 1, -3, 2");
  vector<int> vectorOfInts;
  int mult = 1;
  for (int x=0; x<originalString.length(); ++x)
  {
    if (isdigit(originalString[x]))
    {
      vectorOfInts.push_back(mult * (originalString[x] - 48));
       mult = 1;
    }
     else if (originalString[x] == '-')
    {
      mult = -1;
    }
  }

 for (int i=0; i <vectorOfInts.size(); i++)
   {
     cout << vectorOfInts[i] << " ";
   }
}

If you get rid of the commas, you can convert the string to an input string stream, from which you can get your integers easily:

1
2
3
4
5
6
vector<int> doit(string s)
{
    s.erase(remove(s.begin(), s.end(), ',')); // get rid of commas
    istringstream buf(s); // convert to input stream
    return vector<int>(istream_iterator<int>(buf), istream_iterator<int>()); // done
}


online demo: http://ideone.com/3Xipf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::vector<int> to_vector( std::string comma_seperated_integers )
{
    std::vector<int> sequence ;
    constexpr char COMMA = ',' ;

    comma_seperated_integers += COMMA ;
    std::istringstream stm(comma_seperated_integers) ;

    int value ;
    char delimiter ;
    while( stm >> value >> delimiter && ( delimiter == COMMA ) )
          sequence.push_back(value) ;

    return sequence ;
}
Here's one way:
http://www.cplusplus.com/forum/general/7385/

There are, of course, a ton of ways to do this. You can just write your own using getline (to tokenize by comma) and a stringstream and extraction operator (to read the numbers).
Thank you very much everyone. I am grateful for all your help.
Topic archived. No new replies allowed.