cin 不适用于 typecaset

cin doesn't work with typecaset

以下程序无法编译。

#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。如何使用 cin 接受字符的 ASCII 值。我想使用 char 变量来完成。

Q2。如果确保用户输入的值在字符范围内,stat 2总是产生期望的结果。

所以你希望能够输入例如97 输出得到 'a'?然后读入一个实际的 int 并将 int 变量转换为输出中的一个字符。 IE。几乎与你现在所做的相反:

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

如果您想确保输入的字符是有效的,请使用例如std::isalpha or one of the other character classification functions.