这个小程序描述了我在更大项目中遇到的问题:
int main()
{
string str1="11111111";
string str2="22222222";
char a=str1[2];
char *a1=&a;
int var1= atoi(a1);
char b=str2[2];
char *b1=&b;
int var2= atoi(b1);
cout<<var1<<endl;
cout<<var2;
return 0;
}
为什么会这样
1
21
代替
1
2
?
有什么办法可以解决这个问题吗? - 感谢帮助我想了两个小时
最佳答案
您错误地得到了两个结果(即使您的第一个结果恰好符合您的预期)。
问题是 a1
和 b1
都指向一个字符,而 atoi
需要一个以 null 结尾的字符串。
您可以通过构建字符数组而不是复制单个字符来解决此问题:
char a1[2] = { str1[2] }; // C++ compiler supplies null terminator, you supply the size
int var1= atoi(a1);
char b1[] = { str2[2], 0 }; // You supply null terminator, C++ compiler computes the size
int var1= atoi(b1);
关于c++ - 如何从字符串中获取 int(使用类似 char 数组的字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43616187/