gpt4 book ai didi

c++ - 如何将字符数组转换为字符串?

转载 作者:行者123 更新时间:2023-11-30 01:02:35 25 4
gpt4 key购买 nike

我正在编写一个程序来生成一个随机的 16 位数字。我的做法是用字符数组一个一个存储随机数。最终,我想将这个字符数组转换成一个字符串。我该怎么做?

我尝试将它直接转换为字符串,但是当我将它输出到屏幕上时,输出在 16 位数字后面出现了一些奇怪的字符。

#include <iostream>
#include <string>
using namespace std;

int main(){
char acct_num[16];
for(int x = 0; x < 16 ; x++){
acct_num[x] = rand()%10 + '0';
}
acct_num[16] = '\0';

cout<<string(acct_num)<<endl;

}

我只想要 16 位数字作为字符串。

最佳答案

你已经用完了数组的末尾。 C 风格的字符串称为字符串(而不是字符数组)。您已在字符串的末尾正确添加了“\0”,但您已写入 17 个字节,因此您只需要使 char 缓冲区长 17 个字节,这样您的数字就可以有 16 个字节。

使数组长度为 17 个字符:

#include <iostream>
#include <string>
using namespace std;

int main(){
char acct_num[17];
for(int x = 0; x < 16 ; x++){
acct_num[x] = rand()%10 + '0';
}
acct_num[16] = '\0';

cout<<string(acct_num)<<endl;

}

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

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