[英]Problems converting a Char to an Integer in C++
I've been looking for this but the other answers confuse me. 我一直在寻找这个,但是其他答案使我感到困惑。 I just want to convert a char to an integer in C++. 我只想在C ++中将char转换为整数。 I've read something about atoi
function but it does not work for me. 我已经读过一些关于atoi
函数的内容,但是它对我不起作用。 Here's my code: 这是我的代码:
string WORD, word;
cout<<"PLEASE INPUT STRING: "<<endl;
getline(cin,WORD);
for(int i=0; i<WORD.length(); i++){
if(isdigit(WORD[i])){
word = atoi(WORD[i]); //Here is my problem.
}else{
cout<<"NO DIGITS TO CONVERT."<<endl;
}//else
}//for i
BTW, I checked if the char is a digit first. 顺便说一句,我先检查字符是否是数字。
atoi takes a NUL terminaled string. atoi采用NUL终端字符串。 It doesn't work on a single character. 它不适用于单个字符。
You could do something like this: 您可以执行以下操作:
int number;
if(isdigit(WORD[i])){
char tmp[2];
tmp[0] = WORD[i];
tmp[1] = '\0';
number = atoi(tmp); // Now you're working with a NUL terminated string!
}
If WORD[i]
is a digit, you can use the expression WORD[i] - '0'
to convert the digit to a decimal number. 如果WORD[i]
是数字,则可以使用表达式WORD[i] - '0'
将数字转换为十进制数。
string WORD;
int digit;
cout<<"PLEASE INPUT STRING: "<<endl;
getline(cin,WORD);
for(int i=0; i<WORD.length(); i++){
if ( isdigit(WORD[i]) ){
digit = WORD[i] - '0';
cout << "The digit: " << digit << endl;
} else {
cout<<"NO DIGITS TO CONVERT."<<endl;
}
}
**You can solve it by : **您可以通过以下方法解决:
digit = WORD[i] - '0';
replace it by your wrong line . 用错误的线代替它。
and you can 你可以
adding :edited for cruelcore attention** 添加:编辑,以吸引残酷的关注**
By answer by user4437691, with an addition. 由user4437691回答,并附加了一个内容。 you can not set string to int using =
, but you can set it to char, according to this reference: http://www.cplusplus.com/reference/string/string/operator=/ 您不能使用=
将string设置为int,但是可以根据以下参考将其设置为char: http : //www.cplusplus.com/reference/string/string/operator=/
So cast it to char. 因此将其转换为char。
word = (char) (WORD[i] - '0'); 字=(字符)(WORD [i]-'0');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.