【问题标题】:When I input a number in char type, why i can't get a whole number?当我输入char类型的数字时,为什么我不能得到一个整数?
【发布时间】:2020-10-22 15:43:13
【问题描述】:

我在 char 类型变量中输入了一个数字。像 12 或 22。但是,控制台显示 1 或 2。 我如何在控制台中获得整数 12 ,22?

#include <iostream>

int main()
{
    using namespace std;

    char a = 0;
    cin >> a;
    cout << a << endl;
    return 0;
}

这是控制台结果。

12
1

C:\Users\kdwyh\source\repos\MyFirstProject\Debug\MyFirstProject.exe(프로세스 18464개)이(가) 종료되었습니다(코드: 0개).
이 창을 닫으려면 아무 키나 누르세요...

我不使用 int、string 和其他东西的原因是因为我想在一个变量中同时获取数字和字符。 所以我想同时看到组合数字和字符的结果。 在那个过程中,我无法得到一个整数。

#include <iostream>

using namespace std;

int index = 0;
constexpr int pagenum = 10;

void chapterlist(void);

void nextlist(void);

void beforelist(void);

void movechapter(char a);


int main(void)
{   
    char userin = 0;
    bool toggle = 0;
    
    cout << "결과를 볼 챕터를 고르시오." << endl;
    
    chapterlist();

    cout << "다음 페이지로 이동: n" << endl;
    
    cin >> userin;

    if (userin == 'n')
    {
    backflash:

        while(toggle == 0)
        {
            nextlist();
            cin >> userin;

            if (userin == 'b')
            {
                toggle = 1;
                goto backflash;
            }
            else if (userin == 'n')
                continue;
            else
            {
                system("cls");
                movechapter(userin);
                break;
            }
        }

        while(toggle == 1)
        {
            beforelist();
            cin >> userin;

            if (userin == 'n')
            {
                toggle = 0;
                goto backflash;
            }
            else if (userin == 'b')
                continue;
            else
            {
                system("cls");
                movechapter(userin);
                break;
            }
        }
    }
    else
    {
        system("cls");
        movechapter(userin);
    }
    
    return 0;
}

void chapterlist(void)
{
    int x = 0;

    for (x = index + 1; x <= index + 10; x++)
        cout << "Chapter." << x << endl;
}

void nextlist(void)
{
    system("cls");

    cout << "결과를 볼 챕터를 고르시오." << endl;

    index = index + pagenum;
    chapterlist();

    cout << "다음 페이지로 이동: n" << endl;
    cout << "이전 페이지로 이동: b" << endl;
}

void beforelist(void)
{
    system("cls");

    cout << "결과를 볼 챕터를 고르시오." << endl;

    index = index - pagenum;
    chapterlist();

    cout << "다음 페이지로 이동: n" << endl;
    cout << "이전 페이지로 이동: b" << endl;
}

void movechapter(char a)
{
    cout << "선택한 Chapter." << a << "의 결과입니다." << endl;
}

在 movechapter() 中,控制台显示 a 是 1 还是 2,而不是 12、22。

【问题讨论】:

  • 因为'1' 是一个字符,'2' 在字符串"12" 中也是如此。您读取“字符”,任何转换(例如到int)都会在读取字符后发生。
  • 嗯,我必须决定我想问什么。如此复杂,即使我看到了。
  • 情况变得更糟了。 ASCII 是基本字符集,但非常有限。于是 UTF-8、unicode 和 UTF-16 出现了。 (多字节字符)。 C 和 C++ 都提供基本输入例程,允许读取各种字符和数字类型,为您处理从 char 到数字类型的转换。宽字符类型需要对输入进行特殊处理(尽管 UTF-8 通常由基本输出例程自动处理)
  • 如果你能评论一下那些韩文字母的意思就好了,这样我们可以更好地理解你的代码
  • 不确定我是否正确理解您的代码,您希望用户输入nb 转到下一页或上一页,并输入一个数字转到相应的章节号码?

标签: c++ char cin cout


【解决方案1】:

首先,你要了解什么是char类型。

字符类型:它们可以表示单个字符,例如“A”或“$”。最基本的类型是char,它是一个单字节字符。还为更宽的字符提供了其他类型。

为简化起见,char 只能包含一个字符。

与您的代码一样,“12”实际上是 2 个单独的字符,“1”和“2”,这就是它不起作用的原因。

您可以将int 类型声明为int 类型,而不是将a 声明为char 类型,该类型旨在保存数字。所以你会有:

int a = 0;

但是,请注意int 通常具有最大值 2^31。

或者您可以使用std::string 来存储字符串。但是,请注意,如果您希望对 string 类型进行任何计算,则需要先将它们转换为数字类型:

int myInt = std::stoi(myString);

编辑:

所以我在您更新后重新检查了您的代码,在您的情况下使用 std::string 没有任何问题。您仍然可以通过以下方式检查用户是否输入了nb

if (userin == "n")

请注意,您将在要检查的内容周围使用双引号或"letter"

另一方面,您可以使用:

if(std::all_of(userin .begin(), userin.end(), ::isdigit))

检查用户是否输入了数字。

【讨论】:

  • 所以如果我想得到'12',我必须使用char数组吗?
  • 是的,您可以使用字符数组。这就是 C 中的“字符串”:一个以空字符结尾的字符数组。但如果您使用 C++,更好的选择是使用std::string。如果您希望有一个可以进行算术运算的值,那么您可以改用integer type,例如“int”。
  • @유장현 取决于您的代码目标。如果您知道用户只会输入数字,则可以使用数字类型,例如 intlong
  • @Ranoiaetep 好的,我尝试使用 std::string。感谢您回答我的问题!
【解决方案2】:

您应该将字符读入字符串,然后将该字符串转换为 int。使用getline() 之类的东西而不是cin &gt;&gt; a 来读取输入也可能更有意义。

#include <string>
#include <iostream>
#include <stdexcept>
#include <stdio.h>

int main() {
    std::string input_string;
    /* note that there is no function that will convert an int string
       to a char, only to an int. You can cast this to a char if needed,
       or bounds check like I do */
    int value;

    while(1) {
        getline(std::cin, input_string);
        /* std::stoi throws std::invalid_argument when given a string
           that doesn't start with a number */
        try {
            value = std::stoi(input_string);
        } catch (std::invalid_argument) {
            printf("Invalid number!\n");
            continue;
        }
        /* You wanted a char, the max value of a `char` is 255. If 
           you are happy for any value, this check can be removed */
        if (value > 255) {
            printf("Too big, input a number between 0-255\n");
            continue;
        }
        break;
    }
    printf("Number is %hhu\n", value);
}

【讨论】:

  • 对我来说有些困难......但我明白你想对我说什么。谢谢!
  • 您不需要编写类型说明符,而是使用std::cout 来打印(代码是C++)。
【解决方案3】:

虽然char 只是一个数字,但这里假定它的意思是“单个字符”用于输入。通过要求其他内容来解决此问题:

int a = 0;

您始终可以根据需要将其转换为 char,当然要进行溢出测试。

【讨论】:

  • 我使用 char 的原因是我想获得两种类型的输入。像 12 和“R”。所以我想在控制台中同时获取它们。
  • 您可以有两种不同类型的变量,例如int xchar y 然后std::cin &gt;&gt; x &gt;&gt; y 将分别处理每种类型。
  • 感谢您的评论!好吧,这种方式似乎可以使程序更容易。那我试试!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
相关资源
最近更新 更多