[英]Assigning an integer into index in char * pointer array
Redoing my previous question since I didn't provide enough detail.重做我之前的问题,因为我没有提供足够的细节。
I have a char pointer array, char* token[100]
.我有一个字符指针数组, char* token[100]
。 Let's say I have a double-digit number, like 33.假设我有一个两位数的数字,比如 33。
How do I assign this int into an index in the token array, so that when I print out that token it will give me 33 and not some sort of ASCII value?如何将此 int 分配到令牌数组中的索引中,以便当我打印出该令牌时,它会给我 33 而不是某种 ASCII 值?
char* token[100];
int num = 33;
//How do I assign num into a specific token index, like for example:
token[1] = num;
//When I print out that token index, I want 33 to be printed out
cout << token[1] << endl; // I want to have 33 be the result. Right now I have '!' as an output
It seems you mean something like the following看来你的意思是这样的
#include <iostream>
#include <string>
#include <cstring>
int main()
{
char * token[100] = {};
int num = 33;
std::string s= std::to_string( num );
token[1] = new char[s.size() + 1];
std::strcpy( token[1], s.c_str() );
std::cout << "token[1] = " << token[1] << '\n';
delete [] token[1];
return 0;
}
The program output is程序输出是
token[1] = 33
If you are not allowed to use C++ containers and functions then the program can look the following way如果不允许使用 C++ 容器和函数,则程序可以如下所示
#include <iostream>
#include <cstdio>
#include <cstring>
int main()
{
char * token[100] = {};
int num = 33;
char buffer[12];
std::sprintf( buffer, "%d", num );
token[1] = new char[std::strlen( buffer ) + 1];
std::strcpy( token[1], buffer );
std::cout << "token[1] = " << token[1] << '\n';
delete [] token[1];
return 0;
}
I'm convinced, from comments, that you want an array of integer types.从评论中,我确信您需要一个整数类型的数组。 If we get further clarification about why this needs to be a char
array, I'll update my answer, but from all available information it seems like you really want an integer-type array.如果我们进一步澄清为什么这需要是一个char
数组,我会更新我的答案,但从所有可用信息来看,您似乎真的想要一个整数类型的数组。
#include <iostream>
int main(int argc, char** argv)
{
int token[100] = {};
int num = 33;
token[1] = num;
std::cout << token[1] << std::endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.