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.
我正在寻找将int 1-9的for循环转换为字符串数组,看了一下我发现了一些代码将int转换为字符串但是当我试图将它放在for循环中并且make时一个字符串数组我一直在收到错误。
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.
任何帮助将非常感激。
2 个解决方案
#1
3
c++ uses 0 based indexing. That means string str[9]
supports indexes 0->8
not 1->9
. In this loop:
c ++使用基于0的索引。这意味着字符串str [9]支持索引0-> 8而不是1-> 9。在这个循环中:
for (int num = 1; num <= 9; num++) {
you are attempting to index from 1->9
. You should change it to this:
你试图从1-> 9索引。您应该将其更改为:
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++
}
#2
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" :
只需将运算符更改为“<9”而不是“<= 9”:
for (int num = 1; num < 9; num++)
#1
3
c++ uses 0 based indexing. That means string str[9]
supports indexes 0->8
not 1->9
. In this loop:
c ++使用基于0的索引。这意味着字符串str [9]支持索引0-> 8而不是1-> 9。在这个循环中:
for (int num = 1; num <= 9; num++) {
you are attempting to index from 1->9
. You should change it to this:
你试图从1-> 9索引。您应该将其更改为:
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++
}
#2
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" :
只需将运算符更改为“<9”而不是“<= 9”:
for (int num = 1; num < 9; num++)