【问题标题】:How to read all the numbers in the string one by one into array (c++)如何将字符串中的所有数字一一读入数组(c++)
【发布时间】:2010-12-16 09:33:42
【问题描述】:

我看到了一个类似的问题,但答案在我的 Visual C++ 6 上不起作用。 我有一个 CString(可视化 C++ String 类),数字用逗号分隔:

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

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

附: 这是我失败的尝试:

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 会运行。 有任何想法吗? 谢谢

【问题讨论】:

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


    【解决方案1】:

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

    不过,如果你能保证你的字符串总是这样,你可以试试:

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

    这将让您不必进行提升等操作。

    【讨论】:

    • 谢谢!看起来它现在有效!做更多的测试,我会报告回来
    • 这是在我的情况下最容易工作的一个(至少现在是这样),所以我给了它正确的一点:) Mihran 的也很有趣......
    【解决方案2】:
    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;
    }
    

    【讨论】:

    • 我也注意到了你的答案,现在它写在我的助手类中作为备份。谢谢大家!
    【解决方案3】:
    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);
    

    【讨论】:

      【解决方案4】:
      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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-27
        • 2022-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多