0

In my program I recieve a string: "09:07:38,50,100" (the numbers will be changing, only commas are consistent)

My desired output would be seperating the string into 3 different variables for use in other things.

like so:

a = 09:07:38

b = 50

c = 100

Currently I tried splitting the string by seperating at commas, but I still lack the ability to put the data into different variables, or atleast the knowledge on how to. Here is my current code:

#include<iostream>
#include<vector>
#include<sstream>

int main() {
    std::string my_str = "09:07:38,50,100";
    std::vector<std::string> result;

    std::stringstream s_stream(my_str); //create string stream from the string

    while(s_stream.good()){
        std::string substr;
        getline(s_stream, substr, ','); //get first string delimited by comma
        result.push_back(substr);
    }

    for(int i = 0; i<result.size(); i++){ //print all splitted strings
        std::cout << result.at(i) << std::endl; 
    }

}

Appreciate any help, thanks!

  • what's the type for the variables you want the data stored in ? (ie a,b,c) – user Apr 17 '20 at 08:20
  • I want them stored as strings std::string a = ""; std::string b = ""; std::string c = ""; – AEDNordic Apr 17 '20 at 08:28
  • Note that your reading loop suffers from the same problem as [this](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – molbdnilo Apr 17 '20 at 08:29
  • 1
    `std::string a = result[0]` etc. Maybe check if `result.size() == 3` before that. You can also transform them into numbers, like `double a = std::stod(input)`. – Aziuth Apr 17 '20 at 08:30
  • looks to me like all you want is `std::string a = result[0];` – user Apr 17 '20 at 08:33

2 Answers2

0

The stoi function is what you require.

a = stoi(result.at(i));
std::cout << a;
Cibin Joseph
  • 884
  • 1
  • 10
  • 14
Parvathi
  • 16
  • 2
0

I think is a good idea to approach this kind of problem using regular expressions:

#include <string>
#include <boost\regex.hpp>

int main()
{
    std::string my_str = "09:07:38,50,100";

    std::string a,b,c;

    boost::regex regEx("(\\d{2}:\\d{2}:\\d{2}),(\\d*),(\\d*)");

    if(boost::regex_match(my_str, regEx, boost::match_extra))
    {
        boost::smatch what;
        boost::regex_search(my_str, what, regEx);

        a = what[1];
        b = what[2];
        c = what[3];
    }

    std::cout<< "a = " << a << "\n";
    std::cout<< "b = " << b << "\n";
    std::cout<< "c = " << c;
}
SeventhSon84
  • 364
  • 1
  • 4