c++ - 如何只接受整数而忽略其他数据类型?

标签 c++

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

我正在制作一个程序,这个程序需要进行错误检查。 那么,如何才能只接受整数而忽略其他数据类型呢?

例如:

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

当我的代码运行时:

输入:1 嘿,我想跳舞

输出:我想跳舞

///

我想要的:

案例一: 输入:1

嘿,我想跳舞

输出:嘿,我想跳舞

案例二: 输入: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.";
    }
}

关于c++ - 如何只接受整数而忽略其他数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46345430/

相关文章:

c++ - 如何从 c++ 的一个方面(aspect c++)释放或删除函数中分配的对象?

c++ - 在编译时获取 std::array 中的元素数量

c++ - 在 MSVC 中配置 Qt 项目设置

c++ - VS Test Explorer为什么不显示我的C++自定义异常消息?

c++ - move std::unique_ptr的构造函数/分配:内存重新分配?

c++ - 如何在循环中表示不再输入字符串 ss while (cin >> ss)

c++ - 如何将访问者界面适配为迭代器界面?

c++ - 使用 boost :thread 的可运行类

c++ - 从 OpenMP 循环内部访问和编辑 aN ma 时出错

c++ - 使用不等于与等于时是否有任何性能差异