简体   繁体   中英

How to convert string array to integer array in C++?

I have a string of non-uniform space separated integers,I want to do some arithmetic operations on the elements so I have decided to first convert the string to integer array. Below is my approach:

    string s;                //let s="1   2 30 54  899 2 7   3 1";
    cin>>s;
    int n=s.length();
    vector<int>arr(n);

    for(int i=0;i<n;i++)
    {
        if(s[i]==' ')continue;
        else{
            arr.push_back(s[i]-'0');
        }
    }
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<endl; // arr should be{1,2,30,54,899,2,7,3,1};
    }

What is wrong in this approach?

What is wrong in this approach?

  • operator>> only extracts until the first encountered character in std::cin that satisfies std::isspace() , so s could not possibly be initialized to a string containing spaces in your program.
  • You assume that the length of the string n should be the length of the array. The number of characters is not equal to the number of whitespace-separated values.
  • You initialize arr to length n and then use push_back() . You should be default initializing the vector so it starts empty.
  • You read each character separately from the string and push_back() each digit as a separate element.

You can use std::getline() to initialize the string from std::cin and std::istringstream to simplify extracting the formatted integers:

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

int main()
{
    std::string s;
    std::getline(std::cin, s);
    std::istringstream iss(s);
    std::vector<int> arr;

    for (int i; iss >> i;) {
        arr.push_back(i);
    }

    for(auto& v : arr)
    {
        std::cout << v << std::endl;
    }
}

Godbolt.org

You 'll loop all elements and convert with stoi . Then put it in the int-array.

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