如何仅接受整数并忽略其他数据类型

How to accept integer only and ignore other data types?

本文关键字:其他 数据类型 何仅接 整数      更新时间:2023-10-16

我是C 的初学者,我想知道您是否可以帮助我。

我正在制作程序,并且此程序需要进行错误检查。那么,我如何仅接受整数并忽略其他数据类型?

例如:

int tilenumber;
cin >> tilenumber;
cin.clear();
cin.ignore();
cin >> words;

我的代码运行时:

输入:1 嘿,我想跳舞

输出:我想跳舞

///

我想要的:

案例1:输入:1

嘿,我想跳舞

输出:嘿,我想跳舞

案例2:输入:1E

嘿,我想跳舞

输出:嘿,我想跳舞

为什么我的代码不工作?

我试图用上述代码解决我的问题,但它不起作用。

谢谢。

读取整个字符串并使用std :: stoi函数:

#include <iostream>
#include <string>
int main() {
    std::cout << "Enter an integer: ";
    std::string tempstr;
    std::getline(std::cin, tempstr);
    try {
        int result = std::stoi(tempstr);
        std::cout << "The result is: " << result;
    }
    catch (std::invalid_argument) {
        std::cout << "Could not convert to integer.";
    }
}

替代方案是使用std :: stringstream并进行解析:

#include <iostream>
#include <string>
#include <sstream>
int main() {
    std::cout << "Enter an integer: ";
    std::string tempstr;
    std::getline(std::cin, tempstr);
    std::stringstream ss(tempstr);
    int result;
    if (ss >> result) {
        std::cout << "The result is: " << result;
    }
    else {
        std::cout << "Could not convert to integer.";
    }
}