繁体   English   中英

C ++在具有多个定界符的字符串中提取整数

[英]C++ Extracting the integer in a string with multiple delimiters

我正在尝试从字符串中提取整数。 这有什么问题吗? 我只有第一个价值。 我如何才能使它即使在字符串为零的情况下也能正常工作?

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

仔细观察这一行:

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

请注意,此条件始终为真,因此您始终会unget标点符号。 然后,当需要数字时,下一次读取将始终失败,因为它将读取标点符号。 更改|| &&的应该可以解决此问题。

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

您可以通过升压拆分完成此任务。

   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

这会将字符串更改为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;
}

希望这会帮助你。

这适合我的目的,在其中我可以提取整数并在必要时添加定界符。 同样适用于不同格式的字符串。 (我没有boost 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();
      }
   }
}

您也可以尝试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM