如何使用 ifstream 检查文件中变量的类型?

How to check the type of a variable from a file with ifstream?

我在文件(由 ifstream 打开)中有一个流,其中包含 double 和一些 string,但我不知道它们的位置。例如:

1 2 3 4 g 3 2 t 1 d

所以我必须像上面那样读取一个流,但是我不知道如何在读取之前区分变量的类型。

如何使用 ifstream 并且不知道变量的顺序?

您可以 peek() 流中的下一个字符,如果它是数字或符号,则将下一个值读取为 double,否则将其读取为 string .

否则,只需从流中读取所有内容作为 string,然后使用 std::stod()std::strtod() 尝试将每个 string 转换为 double,并检查转换是否失败。

如果您确定您的数字是整数,请使用下面的代码。如果不是,请将 vectemp 中的 int 替换为 double

#include <fstream>
#include <vector>
#include <fstream>

int main()
{
    std::vector<int> vec;
    std::ifstream file {"fileLocation"};
    while(file.peek() != EOF)
    {
        if (isdigit(file.peek())){
            int temp;
            file >> temp;
            vec.push_back(temp);
            file.seekg(file.tellg() + file.gcount());

        }

        else
            file.seekg(static_cast<int>(file.tellg()) + 1);
    }
    for(auto const & el : vec ) std::cout << el << " ";


}