简体   繁体   中英

Converting an int into string array

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.

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++
}

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++)

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