-1

I am trying to convert a string that I have already parsed with spaces into a int array:

    //example of string before parsing
    arrElement = "1,2,3";

    //parsing
    for(int i =0; i < size; i++){
        if(arrElements[i] == ','){
            arrElements[i] = ' ';
        }
    }
    //string is now "1 2 3"

    //trying to convert numbers only into int
    stringstream str;
    int intCount = 0;
    int intNum[size];
    for(int i = 0; i < size; i++){
        str << arrElements[i];
        if(str == " ") {
        }
        else {
            str >> intNum[intCount];
            intCount++;
        }
    }

I am currently getting the result there are five integers reads, instead of the three in the example I made. In addition when I print out the array, I am completely different numbers:

    209664128 32764 0 0 0

I sort of understand the issue, but I am new c++ so I could be wrong, and I am unsure how to resolve this issue. Any help would be greatly appreciated.

4
  • related/dupe: stackoverflow.com/questions/17724925/… Commented Sep 29, 2016 at 20:04
  • int intNum[size]; -- If size is a variable (not a constant), then this is not legal C++. C++ requires constants when specifying the number of entries in an array. Commented Sep 29, 2016 at 20:05
  • How would I make it so that the array will exatcly fit the size of the the integers. I can only make an array size so big, then I would have to shorten it eventually. Commented Sep 29, 2016 at 21:18
  • @TitustheTitan - std::vector<int> intNum(size); Commented Sep 30, 2016 at 14:17

1 Answer 1

0

Here are some minimal modifications to make your example working. I think you should avoid the successive calls between std::stringstream::operator>> and std::stringstream::operator<<.

//example of string before parsing
std::string arrElements = "1,2,3";

//parsing
for(int i =0; i < arrElements.size(); i++){
    if(arrElements[i] == ','){
        arrElements[i] = ' ';
    }
}
//string is now "1 2 3"

//trying to convert numbers only into int
stringstream str(arrElements);
int intCount = 0;
static const int size = 3;
int intNum[size];
for(int i = 0; i < size; i++){
    if(str == " ") {
    }
    else {
        str >> intNum[intCount];
        intCount++;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I will probably be using that stringstream edit. Thank you!

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.