1

I'm looking to convert a for loop of int 1-9 to a string array, having looked around I've found some code to convert an int to a string but when I've tried to put it inside a for loop and make a string array I've been getting errors.

I've been given an assertion failure when I tried this

#include<iostream>
#include <sstream> 
#include <string> 
using namespace std;
int main()
{
    string str[9];

    for (int a = 1; a <= 9; a++) {
        stringstream ss;
        ss << a;
        str [a] = ss.str();
        cout << str[a];
    }

    return 0;
}

And when I tried this the program kept crashing

#include<iostream>
#include <sstream>  
#include <string>  
using namespace std;
int main()
{
    ostringstream str1 [9];

    for (int num = 1; num <= 9; num++) {
        str1[num]<< num;
        string geek = str1[num].str();
        cout << geek << endl;

    }

    return 0;

}

Any help would be really appreciated.

1
  • 1
    str[9] is out of bounds. Commented Oct 13, 2017 at 22:37

2 Answers 2

3

c++ uses 0 based indexing. That means string str[9] supports indexes 0->8 not 1->9. In this loop:

for (int num = 1; num <= 9; num++) {

you are attempting to index from 1->9. You should change it to this:

for (int num = 0; num < 9; num++) {

to loop over the whole array. Or better yet use:

std::vector<std::string> str(9); // For dynamic storage duration 
std::array<std::string, 9> str; // For automatic storage duration
int num = 1;
for (auto& currentString : str) {
      currentStr << num++
}
Sign up to request clarification or add additional context in comments.

Comments

0

I think that this is the cause of the crash:

for (int num = 1; num <= 9; num++) 

just change the operator to be "<9" instead of "<=9" :

for (int num = 1; num < 9; num++)

1 Comment

This is misleading, the OP is not counting 10 items, they are counting 9, but the 9 items are from 1->9 inclusive instead of 0->8 inclusive. When you changed to num 1 -> num < 9 now you are only iterating 8 items.

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.