[英]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. 我正在寻找将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. 任何帮助将非常感激。
c++ uses 0 based indexing. c ++使用基于0的索引。 That means
string str[9]
supports indexes 0->8
not 1->9
. 这意味着
string str[9]
支持索引0->8
而不是1->9
。 In this loop: 在这个循环中:
for (int num = 1; num <= 9; num++) {
you are attempting to index from 1->9
. 你试图从
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" : 只需将运算符更改为“<9”而不是“<= 9”:
for (int num = 1; num < 9; num++)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.