如何知道文本文件中的输入是否是 C++ 中的有效数字

how to know if the input from a text file is a valid numeric in c++

本文关键字:是否是 C++ 有效数字 输入 何知道 文件 文本      更新时间:2023-10-16

我是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

我只提供了伪代码来保留特定的实现,因为家庭作业练习似乎有问题;希望这是一个有用的方向的有用指针!