简体   繁体   中英

Comma separated floats in C++

I am trying to separate a list of numbers such as: 34,45,12.3,100,34.6,50

I can do it only if there are no decimals like this:

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

int main()
{
    std::string str = "34,45,12.3,100,34.6,50";
    std::vector<int> vect;

    std::stringstream ss(str);

    int i;

    while (ss >> i)
    {
        vect.push_back(i);

        if (ss.peek() == ',')
            ss.ignore();
    }

    for (i=0; i< vect.size(); i++)
        std::cout << vect.at(i)<<std::endl;

}

The problem here is with the decimals. The above will produce:

34 45 12 3 100 34 6 50

while it should produce:

34 45 12.3 100 34.6 50

basically the above code when it sees a dot '.' it acts as if it was a comma.

Any ideas?

You should use a float and change the code to use float instead of int:

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

int main()
{
    std::string str = "34,45,12.3,100,34.6,50";
    std::vector<float> vect;

    std::stringstream ss(str);

    float i;

    while (ss >> i)
    {
        vect.push_back(i);

        if (ss.peek() == ',')
        ss.ignore();
    }

    for (i=0; i< vect.size(); i++)
    std::cout << vect.at(i)<<std::endl;

}

You should declare float i instead of int i and declare the vector as a vector of floats instead of a vector of integers. This is because 12.4 is not an integer, but a float.

I think your code interprets 12.3 as two different numbers because you haven't declared that number as a float. You vector holds all of the strings as integers, and not floats. If you declared your vectors as floats instead of integers, then your problem should be solved

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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