[英]How to get int from string (string using like a array of char)
this little program describes my problem which I have in bigger project: 这个小程序描述了我在更大的项目中遇到的问题:
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;
}
Why I'm getting 我为什么会这样
1
21
istead of 不是
1
2
? ?
Is there any way to fix this? 有没有什么办法解决这一问题? - thanks for the help I trying to figureout for two hours
- 感谢我帮助我想要两个小时
You get both results by mistake (even though your first result happens to match your expectation). 你错误地得到了两个结果(即使你的第一个结果恰好符合你的期望)。
The problem is that both a1
and b1
point to a single character, while atoi
expects a null-terminated string. 问题是
a1
和b1
指向一个字符,而atoi
指向一个以null结尾的字符串。
You can fix this problem by constructing character arrays instead of copying individual characters: 您可以通过构造字符数组而不是复制单个字符来解决此问题:
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);
Use std::stoi()
and std::string::substr()
especially if you have std::string
already: 使用
std::stoi()
和std::string::substr()
特别是如果你已经有std::string
了:
std::string str1="11111111";
std::string str2="22222222";
int var1= std::stoi( str1.substr( 2, 1 ) ); // third symbol, 1 symbol long
int var2= std::stoi( str2.substr( 2, 1 ) );
atoi expects a pointer to a null-terminated string of char. atoi期望一个指向以null结尾的char字符串的指针。 You pass a pointer to a char.
您将指针传递给char。 What happens is undefined.
发生了什么是未定义的。 You better use std::stoi instead of atoi since atoi has some fallacies: What is the difference between std::atoi() and std::stoi?
你最好使用std :: stoi而不是atoi,因为atoi有一些谬误: std :: atoi()和std :: stoi有什么区别?
atoi
wants a pointer to the first element of a zero-terminated sequence of characters. atoi
想要一个指向零终止字符序列的第一个元素的指针。
You're passing it a pointer to a single character, leaving undefined behaviour in your wake. 你传给它一个指向单个字符的指针,在你的尾迹中留下未定义的行为。
To get the integer value of one of the digits, take its distance from '0'
: 要获取其中一个数字的整数值,请将其与
'0'
距离'0'
:
int var = str1[2] - '0';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.