简体   繁体   English

如何在获取输入后将int转换为char,将char转换为int

[英]how to convert int to char, char to int after get an input

I just jumped in studying cpp and don't know much so far. 我刚刚学习了cpp,到目前为止还不清楚。

I learnt 'if' grammar recently and just made a homework for myself. 我最近学习了“如果”语法,只是为自己做作业。 You get an input from user. 您得到用户的输入。 It can either be a character or number. 它可以是字符或数字。 When he typed a number, it shows what he typed and it needs to be changed to a character according to ASCII table. 当他键入数字时,它会显示他键入的内容,并且需要根据ASCII表将其更改为字符。 And vice-versa. 反之亦然。

I've searched about this for awhile but seems like people are using loops but I haven't learnt it yet. 我已经搜索了一段时间,但似乎人们正在使用循环,但我还没有学过。 So I'm not going to use it in this homework. 因此,我不会在本作业中使用它。

Here comes my code that I've tried, but don't know what's wrong. 这是我尝试过的代码,但不知道出了什么问题。

#include <iostream>

using namespace std;

int main()
{
    cout << "Enter a Number between 65 to 122 or an Alphabet character : ";
    char in_char;

    cin >> in_char;

    if ((in_char) >= 65 && (in_char) <= 122) // checking for alphabet
        cout << in_char << " " << static_cast<int>(in_char) << endl;

    else // if input is not an alphabet, it's a number and it should be turnd to a character
        cout << in_char << " " << static_cast<char>(in_char) << endl;

    return 0;
}

OK, I think I understand what you are wanting to do without a loop. 好的,我想我了解您想要无循环执行的操作。 Though you may need to remove the limit I have placed on integer input to insure a single-digit is input to translate to ASCII '0'->'9' . 尽管您可能需要取消对整数输入的限制,以确保输入的一位数字转换为ASCII'0 '0'->'9' If I follow your question, you want to be able to take either a number or a character, validate it is in the range of [A-Za-z] or [0-9] , and output the corresponding ASCII character and ASCII character value (or vice versa). 如果我按照您的问题进行操作,则您希望可以使用数字或字符,并验证其是否在[A-Za-z][0-9] ,然后输出相应的ASCII字符和ASCII字符价值(反之亦然)。

For Example if the user enters the following, you want similar output to: 例如,如果用户输入以下内容,则需要类似的输出:

    input   output
    -----   -------------------------------------------
       5    '5' 5
     121    'y' 121
       y    'y' 121
     200    error: integer out of range
       =    error: character no within requested range
       P    'P' 80

In order to accomplish this task, you essentially need to attempt a read of an integer, validate whether an unrecoverabel cin.eof() || cin.bad() 为了完成此任务,您基本上需要尝试读取一个整数,并验证是否需要unrecoverabel cin.eof() || cin.bad() cin.eof() || cin.bad() occurs and exit with error. cin.eof() || cin.bad()发生并错误退出。 Otherwise cin.fail() occurs and the input was non-integer and remains in stdin where you can cin.clear() the failbit and then attempt a character read. 否则会发生cin.fail()且输入为非整数,并保持在stdin ,您可以在其中使用cin.clear() ,然后尝试读取字符。

With the character read, you have the same basic validations, except there is no reason to clear the failbit as your attempt to read an integer and then character has failed at that point. 读取字符后,您将具有相同的基本验证,但没有理由清除故障位,因为您尝试读取整数然后字符此时已失败。

On a good read of either int or char , you simply need to perform the wanted validation to insure the int or char was within range and then format your output as desired. 很好地读取intchar ,您只需要执行所需的验证即可确保intchar在范围内,然后根据需要格式化输出。

A short example with necessary validations could be as follows: 一个带有必要验证的简短示例如下:

#include <iostream>

using namespace std;

int main (void)
{
    cout << "Enter a digit or upper or lower case character : ";
    int in_int;
    char in_char;

    if (!(cin >> in_int) ) {    /* attempt read of int */
        /* if eof() or bad() return error */
        if (cin.eof() || cin.bad()) {
            cerr << "(user canceled or unreconverable error)\n";
            return 1;
        }
        cin.clear();            /* clear failbit */
    }
    else {  /* good integer read */
        if (in_int >= 0 && in_int <= 9) {        // checking ASCII [0-9]
            cout << "'" << (char)(in_int + '0') << "' " << in_int << endl;
        }
        else if (in_int >= 'A' && in_int <= 'z') // checking ASCII [A-Za-z]
            cout << "'" << (char)in_int << "' " << in_int << endl;
        else {
            cerr << "error: integer input out of range.\n";
            return 1;   /* return failure */
        }
        return 0;       /* return success */
    }

    if (!(cin >> in_char) ) {    /* attempt read of char */
        /* if eof() or bad() return error */
        if (cin.eof() || cin.bad()) {
            cerr << "(user canceled or unreconverable error)\n";
            return 1;
        }
        else if (cin.fail())    /* if failbit */
            cerr << "error: invalid input.\n";

        return 1;
    }
    else {  /* good character input */
        if (in_char >= 'A' && in_char <= 'z') // checking ASCII [A-Za-z]
            cout << "'" << in_char << "' " 
                    << static_cast<int>(in_char) << endl;
        else
            cerr << "error: character not within requested range.\n";
        return 1;
    }
}

Example Use/Output 使用/输出示例

$ ./bin/cinonechar
Enter a digit or upper or lower case character : 5
'5' 5

$ ./bin/cinonechar
Enter a digit or upper or lower case character : 121
'y' 121

$ ./bin/cinonechar
Enter a digit or upper or lower case character : y
'y' 121

$ ./bin/cinonechar
Enter a digit or upper or lower case character : 200
error: integer input out of range.

$ ./bin/cinonechar
Enter a digit or upper or lower case character : =
error: character not within requested range.

$ ./bin/cinonechar
Enter a digit or upper or lower case character : P
'P' 80

Look things over and let me know if you have further questions. 仔细检查一下,如果您还有其他问题,请告诉我。 You can adjust the test of int value range to correct any misunderstanding I have on the range you intend with your question. 您可以调整int值范围的检验,以更正我对问题所要覆盖范围的任何误解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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