C ++使用多个分隔符提取字符串中的整数

时间:2017-01-24 05:29:11

标签: c++ string stringstream

我正在尝试从字符串中提取整数。这可能有什么问题? 我只得到第一个值。即使字符串中有零,我怎样才能使它工作?

string str="91,43,3,23,0;6,9,0-4,29,24";
std::stringstream ss(str);
int x;
while(ss >> x)
{
    cout<<"GOT->"<<x<<endl;
    char c;
    ss >> c; //Discard a non space char.
    if(c != ',' || c != '-' || c != ';')
    {
        ss.unget();
    }
}

5 个答案:

答案 0 :(得分:3)

仔细观察这一行:

if(c != ',' || c != '-' || c != ';')

请注意,此条件始终为true,因此您始终unget标点字符。然后,下一次读取将始终失败,因为它会在预期数字时读取标点符号。将||更改为&&可以解决问题。

当然,您的代码假定str以非常特殊的方式格式化,并且在给定格式不同的str值时可能会中断。请注意这一点。

答案 1 :(得分:0)

你可以通过提升分割完成这项工作。

   int main() {
      std::stringstream ss;
      std::string inputString = "91,43,3,23,0;6,9,0-4,29,24";
      std::string delimiters("|,:-;");
      std::vector<std::string> parts;
      boost::split(parts, inputString, boost::is_any_of(delimiters));
      for(int i = 0; i<parts.size();i++ ) {
           std::cout <<parts[i] << " ";
      }
   return 0;
   }

输出(只是整数): - 91 43 3 23 0 6 9 0 4 29 24

答案 2 :(得分:0)

这会将字符串更改为char并注销:,; -

#include <iostream>
#include <string>
using namespace std;
int main(){ 
    string str = "91,43,3,23,0;6,9,0-4,29,24";
    str.c_str();  // ex: string a; --> char a[];
    char a[99];
    int j = 0;
    int x;
    for(int i = 0; i < str.length(); i++){
        if (str[i]!=',' && str[i]!=';' && str[i]!='-'){
            a[j] = str[i];
            j++;
        }
    }
    return 0;
}

希望这会对你有所帮助。

答案 3 :(得分:0)

这适合我的目的,我可以提取整数,并在必要时添加分隔符。也适用于不同格式的字符串。 (我没有升级lib,因此更喜欢这种方法。)

int main()
{
   string  str="2,3,4;0,1,3-4,289,24,21,45;2";
   //string  str=";2;0,1,3-4,289,24;21,45;2"; //input2

   std::stringstream ss(str);
   int x=0;

   if( str.length() != 0 )
   {
      while( !ss.eof() )
      {
         if( ss.peek()!= ',' && ss.peek()!=';' && ss.peek()!='-') /*Delimiters*/
         {
            ss>>x;
            cout<<"val="<<x<<endl;
             /* TODO:store integers do processing */
         }
         ss.get();
      }
   }
}

答案 4 :(得分:0)

您也可以尝试:

vector<int> SplitNumbersFromString(const string& input, const vector<char>& delimiters)
{
    string buff{""};
    vector<int> output;

    for (auto n : input)
    {
        if (none_of(delimiters.begin(), delimiters.end(), [n](const char& c){ return c == n; }))
        {
            buff += n;
        }
        else
        {
            if (buff != "")
            {
                output.push_back(stoi(buff));
                buff = "";
            }
        }
    }
    if (buff != "") output.push_back(stoi(buff));

    return output;
}

vector<char> delimiters = { ',', '-', ';' };
vector<int> numbers = SplitNumbersFromString("91,43,3,23,0;6,9,0-4,29,24", delimiters);
相关问题