在C++中确定输入为int或char

Determining input to be int or char in C++

本文关键字:int char 输入 C++      更新时间:2023-10-16

我正在为学校编写一个小程序,用于计算输入数字的阶乘。我在Java方面有很多经验,但这是我第一次使用C++。

我的问题是:我需要能够从用户那里得到一个单一的输入,它要么是整数,要么是字符"q",这意味着应用程序需要退出。

这是我目前的尝试:

#include <stdio.h>
#include <iostream>
#include "Header.h"
using namespace std;
int x=0;
char y;

int main(int argc, char *argv[])
{
    printf("Hello, please enter a number to compute a factorial (or 'q' to quit): ");
    cin >> y;
    x= (y-'0');

if(y=='q')
    {   printf("Thanks for playing!n");
        exit(1);
    }   
    long result= print_Factorial(x);
    cout << x << "!= " << result << "n";
    return result;
}

然而,这种铸造不起作用。如果我输入一个两位数,比如12,它只会将两位数的第一位转换为x,并计算阶乘。我相信这很简单,我错过了什么?

明确的答案或引导我了解更多关于这个问题的信息,任何事情都值得赞赏。

您可以使用一些函数尝试将字符串转换为数字,并可以检查转换是否成功。std::strtol函数就是其中之一:

std::string input;
std::cin >> input;
char* endptr = nullptr;
const char *input_ptr = input.c_str();
long value = std::strtol(input_ptr, &endptr, 10);
if (endptr == input_ptr)
{
    // Input was not a valid number
}
else if (*endptr != '')
{
    // Input starts with a valid number, but ends with some extra characters
    // (for example "123abc")
    // `value` is set to the numeric part of the string
}
else
{
    // Input was a valid number
}

如果你不介意例外情况,那么你可以使用例如std::stoi

std::string input;
std::cin >> input;
int value = 0;
try
{
    size_t endpos = 0;
    value = std::stoi(input, &endpos);
    if (endpos != input.length())
    {
        // Input starts with a valid number, but ends with some extra characters
        // (for example "123abc")
        // `value` is set to the numeric part of the string
    }
    else
    {
        // Input is a valid number
    }
}
catch (std::invalid_argument&)
{
    // Input not a valid number
}
catch (std::out_of_range&)
{
    // Input is a valid number, but to big to fit in an `int`
}

获得第一个数字的原因是您使用cin>>y;其中y是一个字符,它包含一个字符。所以你只得到一个角色。

您可能想做的是将答案作为一个字符串,一旦您检查到该字符串不是=="q",就可以将其转换为int。

#include <iostream>
#include <sstream>
int main() {
    std::string in;
    std::cout << "Please enter a digit: ";
    while(std::cin >> in) {
        std::cout << "Input: " << in << std::endl;
        if(in.size() == 1) {
            if(in[0] == 'q' || in[0] == 'Q') {
                std::cout << "Quit" << std::endl;
                return 0;
            }
        }
        std::istringstream parse(in);
        int value;
        if(parse >> value) {
            if(parse.eof()) {
                std::cout << "Success" << std::endl;
                return 0;
            }
        }
        std::cout << "Please try again: ";
    }
    std::cerr << "This should not happen <control + d>" << std::endl;
    return 1;
}

您的用户可以输入任何一行文本,您必须读取"一行文本"才能验证。

#include <iostream>
#include <string>
#include <stdexcept>
int main()
{
    std::string text;
    std::getline(std::cin,text);
    if(text.size()==1 && text[0]=='q')
    { 
        std::cout << "quit command"; 
        return 0; 
    }
    try
    {
        int i = std::stoi(text); //may throw if text is not convertible
        /* whatever elaboration and output */
        return 0;
    }
    catch(const std::exception& e)
    {
        std::cout << "bad input: " << text << 'n';
        std::cout << "caused excpetion: " << e.what() << std::endl;
    }
    return 3; //means "excpetion thorown"
}