在主函数中,有各种不同模板类型(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/