如何将字符串中的所有数字一一读入数组(c++) [英] How to read all the numbers in the string one by one into array (c++)

查看:44
本文介绍了如何将字符串中的所有数字一一读入数组(c++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一个类似的问题,但答案在我的 Visual C++ 6 上不起作用.我有一个 CString(可视化 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";

并且我希望他们将它们一一放入一个 int 数组中.我尝试了 stringstream,但它只给了我第一个 int.有人可以帮忙吗?

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

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

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

推荐答案

问题在于 stream >>当 n 遇到字符串中的 , 时失败.您不能以这种方式标记字符串 - 而是查看诸如 boost 之类的库,它提供了一个很好的标记器.

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.

这篇关于如何将字符串中的所有数字一一读入数组(c++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆