简体   繁体   中英

cin doesn't work with typecaset

The following program doesn't compile.

#include <iostream>
#include <cstdio>
using namespace std;

int main(){
    char c;
    cin >> (int)c;       // stat 1
    //scanf("%d", &c);   //stat 2; this when complied gives warning
    cout << c << endl;
}

Q1. How to use cin to accept ASCII value of a character. I want to do it using a char variable.

Q2. If ensured that value input by user lies in the range of character, stat 2 will always produce the desired result.

So you want to be able to input eg 97 and for output get 'a' ? Then read into an actual int and cast the int variable to a character in the output. Ie almost the opposite of what you do now:

int c;
std::cin >> c;
std::cout << static_cast<char>(c);

If you want to make sure that the input is a valid character, then use eg std::isalpha or one of the other character classification functions .

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