Hoornet
Hoornet

Reputation: 1418

How to read all the numbers in the string one by one into array (c++)

I have seen a similar question but the answers did not work on my Visual C++ 6. I have a CString (visual C++ String class) with numbers divided by commas:

CString szOSEIDs = "5,2,6,345,64,643,25,645";

and I'd like them put one by one into a int array. I tried the stringstream but it gives me only the first int. Can someone help?

P.S. This is my failed try:

std::string input;
input = (LPCTSTR)szOSE_IDs;    // convert CString to string 
std::stringstream stream(input);
while(1) {
  int n;
  stream >> n;
  if(!stream)
    break;
  szSQL.Format("INSERT INTO TEMP_TABELA (OSE_ID) values (%d)", n);  // I create SQL from my IDs now available
  if(!TRY_EXECUTE(szSQL)) //This just a runner of SQL
    return false;
}

In this case I would only get the first number (5) and only my 1st SQL would run. Any ideas? Thank you

Upvotes: 0

Views: 1127

Answers (4)

Michael Smith
Michael Smith

Reputation: 411

CString nums = _T("5,2,6,345,64,643,25,645");
CString num;
std::vector<int> intv;
int pos = 0;
do {
    if ((num = nums.Tokenize(_T(","), pos)) != _T(""))
        intv.push_back(_ttoi(num));
    else
        break;
} while (true);

Upvotes: 0

Umut Tabak
Umut Tabak

Reputation: 1942

typedef size_t pos;
  pos p; 
  string str("5,2,6,345,64,643,25,645");
  string chopped(str);
  string strVal;
  bool flag = 1;
  do{
    p = chopped.find_first_of(",");
    if(p == chopped.npos)
      flag = 0;
    strVal = chopped.substr(0,p);
    chopped = chopped.substr(p+1);
    //cout << chopped << endl;
    cout << strVal << endl;

  }while(flag);

Upvotes: 0

Nim
Nim

Reputation: 33655

The problem is that stream >> n fails when it hits the , in your string. You can't tokenize the string this way - instead look at a library such as boost which provides a nice tokenizer.

However if you can guarantee that your string always looks like this, you can try:

  int n;
  while (stream >> n)
  {
    // Work with the number here
    stream.get(); //skip the ","
  }

This will save you having to pull in boost etc.

Upvotes: 1

Mihran Hovsepyan
Mihran Hovsepyan

Reputation: 11108

parse(CString& s, std::vector<int>* v)

{
 int l = s.size();//or something like this
 int res = 0;
 for(int i = 0; i < l; ++i)
 {
  if(s[i] == ',')
  {
   v->push_back(res);
   res = 0;
   continue;
  }
  res*=10;
  res+=s[i] - '0';
 }
 v->push_back(res);
}
int main()
{
 CString s="1,2,3,4,15,45,65,78";
 std::vector<int> v;
 parse(s, &v);
 //...
 return 0;
}

Upvotes: 0

Related Questions