0

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 ?

1
  • Please don't add tags of languages not relevant to the question Commented Apr 24, 2021 at 7:24

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.