我编写了一个模板函数,用于从文件中读取字符串或数值数据,并将数据保存在字符串或整数/双精度的向量中。然后,我使用这些数据通过我编写的另一个代码执行计算。
提前道歉,因为我认为这是一个简单的问题......我无法读取有空格的字符串数据......例如,名字和姓氏。当我想要“Tom Smith”时,我只会得到“Tom”)。从谷歌搜索来看,问题似乎是 >> 而我应该使用 getline 。我尝试用getline(test,100)替换>>,但我得到一个“没有匹配函数调用std :: basic_istringstream ...”类型错误(错误:没有匹配函数调用'std :: basic_ifstream >::getline(double&)')
如果有人能纠正我,我将不胜感激!我似乎无法绕过溪流!
这是一些示例数据和我的代码。我在这里为字符串配置了它。
labelInFile // 一个向量的数据子集标识符
'Tom Smith' 'Jackie Brown' 'John Doe' // 这些名字最终应该作为向量中的元素
#include <algorithm>
#include <cctype>
#include <istream>
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
using namespace std;
template<typename T>
void fileRead( std::vector<T>& results, const std::string& theFile, const std::string& findMe, T& test )
{
std::ifstream file( theFile.c_str() );
std::string line;
while( std::getline( file, line ) )
{
if( line == findMe )
{
do{
std::getline( file, line, '\'' );
std::getline( file, line, '\'');
std::istringstream myStream( line );
myStream >> test;
results.push_back( test );
}
while ( file.get() != '\n' );
}
}
}
int main ()
{
const std::string theFile = "test.txt"; // Path to file
const std::string findMe = "labelInFile";
std::string test;
std::vector<string> results;
fileRead<std::string>( results, theFile, findMe, test );
cout << "Result: \n";
std::copy(results.begin(), results.end(), std::ostream_iterator<string>(std::cout, "\n"));
return 0;
}