如何知道文本文件中的输入是否是 C++ 中的有效数字
how to know if the input from a text file is a valid numeric in c++
我是C++这里的新手,所以即使这似乎是一个简单的问题,我仍然无法弄清楚如何解决它。 所以我有一个文本文件,其中包含一堆数字。有些不是有效的数字,可能是 3.12ad、t3 等,当我使用以下代码时,它无法区分它是否读取了错误的数字,或者它只是完成了读取文件(这两种情况都会给我一个错误消息(。所以我的问题是,我怎样才能捕捉到糟糕的数字情况?谢谢。
int main() {
string line;
int numOfLine = 0;
int inputNum = 0;
float num;
vector<float> arr1;
vector<float> arr2;
ifstream infile11("test.txt");
while (true) {
if (infile11 >> num) {
arr1.push_back(num);
inputNum ++;
cout<<num<<endl;
}
if ((infile11 >> num).fail()) {
cout<<"Error"<<endl;
return 0;
}
}
}
您可以使用正则表达式来检查您得到的字符串是否是数字。如果我没记错的话,在C++中它是在 #include<正则表达式>.这样你就可以使用regex_match((函数了。您的正则表达式可以是这样的:"?\d*(.\d+(?"。正则表达式>
您可以使用标准转换函数(https://en.cppreference.com/w/cpp/string/basic_string/stof(。如果不允许转换,将引发异常。这里有一个例子:
#include <string>
#include <iostream>
#include <vector>
int main()
{
std::vector<std::string> numbers {"3.14", "10", "t3", "toto"};
for (auto& nb : numbers)
{
bool correct = true;
for (auto& c : nb)
{
try
{
std::stof(std::string(&c));
}
catch(const std::exception&)
{
correct = false;
break;
}
}
if (!correct)
{
std::cout << "Cannnot convert [" << nb << "]n";
}
else
{
std::cout << "Correct conversion [" << nb << "]n";
}
}
}
您的问题需要有关什么算作有效数值的更多详细信息。 但是,在那里做出一些假设(例如没有逗号,像 1/2 这样的分数,也不是科学记数法(,您可以在其他答案中建议的正则表达式或转换尝试之外使用一种简单的算法是:
For each line until EOF [end of file]
While current character is whitespace
advance pointer to next character
if currentCharacter = '-'
advance pointer to next character
decimalEncountered = false
For each character
if character >= 0 and character <= 9
advance pointer to next character
else if character == '.'
if (decimalEncountered)
exit loop reporting invalid numeric
else
decimalEncountered = true
else if character == EOF [end of file]
exit loop; no invalid numerics encountered
else if character == line break
go to next iteration of outer loop
else
exit loop reporting invalid numeric
我只提供了伪代码来保留特定的实现,因为家庭作业练习似乎有问题;希望这是一个有用的方向的有用指针!
相关文章:
- C++LDAP检查用户是否是特定组的成员
- 检查某些类型是否是模板类 std::optional 的实例化
- 将错误返回给调用方而不是立即在 C++ 中抛出错误是否是一种好的做法
- 如何检查模板专用化是否是基本模板的子类?
- 如何检查变量是否是C++中的地图?
- C++ Chrono 确定一天是否是周末?
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- 使用类在C++中存储和列出变量/方法是否是一种好的做法
- 代码在 CodeSignal 中工作不正确。不确定这是否是我的代码缺陷
- 如果 C 函数仍然可以间接执行(通过回调函数),那么将它声明为静态函数是否是一种不好的做法?
- MFC 中的窗口消息管理:添加基类调用是否是强制性的?
- 检查 n2 是否是 n1 的倍数后结果错误,但根本没有错误
- C ++:检查它是否是类中的数字
- 传递给放置 new 的指针是否是指向其对象表示形式的非 UB 指针?
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 从 std::string 到 std::array<char,size> 的 memcopy 额外数据是否是一种未定义的行为?
- 有没有办法检查发送到变量的值是否是正确的类型,而它已经在该变量下?
- 如何检查一个模板是否是另一个模板的类成员
- 有没有办法检查用户输入是否是数字?
- 如何知道文本文件中的输入是否是 C++ 中的有效数字