如何仅接受整数并忽略其他数据类型
How to accept integer only and ignore other data types?
我是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.";
}
}
相关文章:
- 防止主数据类型C++的隐式转换
- 哪些 C++ 数据类型是 Metal 和所有其他 C++ 平台共有的
- 只知道运行时的数据类型.如何将数据详细信息隐藏到使用它们的其他类
- 如何将模运算符与其他数据类型一起使用
- 将多种数据类型写入文件时的其他行和额外的数组元素
- 是否要确保一个线程修改的任何数据类型的共享变量对其他线程可见
- 如何仅接受整数并忽略其他数据类型
- 编译器是否有可能检测整数溢出或其他数据类型溢出的可能性
- 是否有可能在c++中为向量(或其他类似的数据类型)编写用户迭代类
- 具有其他类数据类型的C++构造函数
- Streamsize,Streamoff和其他与流相关的数据类型的实际类型是什么
- 其他类数据类型的扩展boost::lexical_cast
- 如何正确地将std::函数用于其他数据类型(在优先级队列中)
- std::vector或其他数据结构中不同类型的对象
- GCC编译器是否可以处理比long / long / int更大的其他数据类型?
- 是否可以在VTK中使用(polyData)编写器来处理来自其他库的数据类型?
- 将curl结果中的字节组解释为其他数据类型的方法
- 在C/ c++或任何其他类似语言中,对变量或数据类型应用&符号时返回的地址类型
- 为什么指向 char 的指针与其他数据类型的指针相比行为不同
- 如何在C++中确定标准库字符串或其他非基本数据类型在内存中的大小