Parse string containing numbers into integer array

前端 未结 3 1987
终归单人心
终归单人心 2020-12-09 04:06

A String is given as an input which consists of numbers and I want to convert it into integer arrays in C++.

#include 
#include 

        
相关标签:
3条回答
  • 2020-12-09 04:41

    i don't know if you find the answer for your updated question or not. if you don't you can easily do it by the code

    for (string::iterator it = num.begin(); it != num.end(); ++it) {
        if (*it == ',') {
            *it = ' ';
        }
        else continue;
    }
    

    this code removes all your colons and replaces them by space. then you can do just normally

    0 讨论(0)
  • 2020-12-09 04:43

    Another means of dealing with a character separated integers list using a vector, which is even perhaps a little more simplistic is more like this:

    string str = "50,2,25,38,9,16";
    vector<int> ints;
    stringstream ss(str);
    int n;
    char ch;
    
    while(ss >> n) {
        if(ss >> ch)
            ints.push_back(n);
        else
            ints.push_back(n);
    }
    

    that way you can move past any character separations (if they exist) first and then default back to grabbing the integers and adding them to the list if they don't (AKA the end of the list)

    0 讨论(0)
  • 2020-12-09 04:56

    The end of file condition is not set upon a succesful parse, you have to check the state of the stream after parsing.

    The second 76 is basically just pure chance. An unsuccesful parse leaves the target operand untouched, and because you did not initialize n, it can be anything.

    A quickfix:

    stream>>n;
    if (stream)
        cout<<n<<endl;
    

    A cleaner fix:

    int n;
    while(stream >> n){
        cout<<n<<endl;
    }
    

    To store those integers, the canonical way is to use std::vector if the number of elements is unknown. An example usage:

    std::vector<int> values;
    int n;
    while(stream >> n){
        ...do something with n...
        values.push_back(n);
    }
    

    However, you can use iterators over streams and use the following:

    // Use std::vector's range constructor
    std::vector<int> values(
         (std::istream_iterator<int>(stream)), // begin
         (std::istream_iterator<int>()));      // end
    
    0 讨论(0)
提交回复
热议问题