c++ - 在 C++ 中将文件输入类型转换为 vector 类型

标签 c++ casting

在主函数中,有各种不同模板类型(float、int、char*)的向​​量。调用此函数以从不同文件读取格式化输入以填充每个 vector 。我的问题来自类型转换,因为

v.push_back((T)(pChar));

不喜欢将 char* 转换为 float(大概是因为小数点)。

问题:有没有一种方法,只要输入文件合适,无论数据类型如何,都可以得到正确的转换? (我考虑过 typeid(); 但我不赞成使用它)

template <class T>
void get_list(vector <T> & v, const char * path)
{
    fstream file;
    const char delim[1]{' '};
    char line[512];
    char * pChar;

    file.open(path, ios_base::in);
    if (file.is_open())
    {
        while (!file.eof())
        {
            file.getline(line, 512);
            pChar = strtok(line, delim);
            while (pChar != NULL)
            {
                v.push_back(pChar);
                pChar = strtok(NULL, delim);
            }
        }
        file.close();
    }
    else
    {
        cout << "An error has occurred while opening the specified file." << endl;
    }
}

这是家庭作业,但这个问题与作业目标没有直接关系。 分配在数据结构/算法类的堆上。

最佳答案

事实上,您不能简单地将字符串转换为任意类型,您需要一些代码来解析和解释字符串的内容。 I/O 库为此提供了字符串流:

std::stringstream ss(pChar);
T value;
ss >> value;
v.push_back(value);

这将适用于所有具有 >>> 重载的类型,包括所有内置数字类型,如 float

或者,您可能想要摆脱讨厌的 C 风格标记化:

T value;
while (file >> value) {
    v.push_back(value);
}

std::copy(
    std::istream_iterator<T>(file), 
    std::istream_iterator<T>(),
    std::back_inserter(v));

至少,将循环更改为

while (file.getline(line, 512))

在读取该行后检查文件状态,这样您就不会处理最后一行两次。

关于c++ - 在 C++ 中将文件输入类型转换为 vector 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26903941/

相关文章:

C++ 3D完美碰撞检测

c++ - 设置类型作为宏参数返回错误 : expected unqualified-id before string constant

c++ - c++中有趣的情况

c++ - 将派生类转换为具有相同公共(public)函数的泛型类类型,同时仍然可以调用派生类的函数

c++ - 我可以避免 Matrix 类的迭代器中的循环依赖吗?

c++ - 如何使用 QuantLib 计算单名债券价格?

c++ - 如何将数据推送到 C++ 中的第二个位置

c++ - 转换成本

c# - 在 C# 中如何将 var 转换为 char 数组。字符数组[8]

Java:具有泛型方法的泛型类