如何将字符串中的所有数字逐个读入数组(c ++)

时间:2010-12-16 09:33:43

标签: c++ visual-c++ string

我见过类似的问题,但答案对我的Visual C ++ 6无效。 我有一个CString(visual C ++ String类),数字除以逗号:

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

我希望他们逐个放入一个int数组。 我尝试了stringstream但它只给了我第一个int。 有人可以帮忙吗?

P.S。 这是我失败的尝试:

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

在这种情况下,我只会得到第一个数字(5),只有我的第一个SQL会运行。 有任何想法吗? 谢谢

4 个答案:

答案 0 :(得分:1)

问题是stream >> n在点击字符串中的,时失败。你不能用这种方式标记字符串 - 而是查看一个像boost这样的库,它提供了一个很好的标记器。

但是,如果您可以保证您的字符串始终如此,您可以尝试:

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

这将节省你必须拉动助推等。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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);

答案 3 :(得分:0)

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);