gpt4 book ai didi

c++ - 将 int 转换为字符串数组

转载 作者:行者123 更新时间:2023-11-30 02:22:55 24 4
gpt4 key购买 nike

我正在寻找将 int 1-9 的 for 循环转换为字符串数组,环顾四周后我发现了一些将 int 转换为字符串的代码,但是当我试图将它放入 for循环并制作一个字符串数组我一直收到错误。

当我尝试这个时,我得到了一个断言失败

#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;
}

当我尝试这个程序时,程序一直崩溃

#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;

}

任何帮助将不胜感激。

最佳答案

c++ 使用基于 0 的索引。这意味着 string str[9] 支持索引 0->8 而不是 1->9。在这个循环中:

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

您正在尝试从 1->9 进行索引。你应该把它改成这样:

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

遍历整个数组。或者更好的是使用:

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

关于c++ - 将 int 转换为字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46738878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com