sarikaya
sarikaya

Reputation: 301

How to split numbers in string correctly?

My input format :

192,21,4 33,2,1 23,7,61

and I want to obtain only numbers.

#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;

int strtoint(const std::string str){      //converting the string to integer
    float a = str.length();
    int result = 0;
    for(int i=1; i<=str.length(); i++){
            result+=(str[i-1]-'0')*pow(10,(a-1));
            a--;
    }
    return result;
}

int main ()
{
  string name;
  string segment;
  while(getline (cin,name, ' ')){
        stringstream test(name);
        while(getline(test, segment, ','))
            {
              cout << segment <<" "<<strtoint(segment)<<endl;
            }
  }
  return 0;
}

I didn't obtain last one (61). So output is 192 21 4 33 2 1 23 7.

How do I get all the numbers?

Upvotes: 2

Views: 272

Answers (3)

jaho
jaho

Reputation: 5002

How about:

int main()
{
    std::string input = "192,21,4 33,2,1 23,7,61";  
    std::stringstream lineStream(input);    

    std::vector<int> numbers;
    std::string number;

    while (std::getline(lineStream, number, ','))
    {
        numbers.push_back(atoi(number.c_str()));
    }

    for (int n : numbers)
    {
        std::cout << n << " ";
    }
}

Upvotes: 1

Joy R&#234;
Joy R&#234;

Reputation: 159

If you do not input a space (" ") after 61, getline will not return, and thus never print 61. It does not return upon receiving newline character ("\n") if you specify a delimeter.

Upvotes: 0

Peter
Peter

Reputation: 5728

I don't know why your implementation doesn't work with the inputs you provided - Derek showed in the comments that is should work. Any extra characters that it understands wrong would be interpreted as numbers by your program, so if there's some hidden input (tab, newline, dot instead of comma, etc.) it should output garbage instead of 61, rather than nothing.

Rather than using getline, I would use other ways to split a string. Primarily because getline implies that it reads an entire line and therefore it can be hard for others to understand what you actually do. See this thread for how to split a string: Split a string in C++?

When parsing numbers you will run into issues as soon as you run into unexpected characters, e.g."a". There are better and simpler ways to parse numbers: How to parse a string to an int in C++?

Upvotes: 1

Related Questions