简体   繁体   中英

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++. I've read something about atoi function but it does not work for me. 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. 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.

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. 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=/

So cast it to char.

word = (char) (WORD[i] - '0');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM