2011-02-28 59 views
0

要使用我为执行计算而编写的代码,我需要从外部文本文件读入数据(数字和字符串),并将它们存储在字符串或ints /双打。我已经写了一个模板函数来做到这一点。 CashCow,Howard Hinnant和wilhelmtell对以前的问题提供了帮助。C++:从外部文件读取数据;我的代码在代码结束前停止读取的问题

该函数似乎适用于整数/双精度,但我有一个字符串数据的问题。

我需要从我的外部文件的一行数据进入一个向量,但函数读取多行。这是我的意思。比方说,这是在外部文本文件(如下图):


vectorOne //标识为数据的子集为一个矢量

“1”“2”“3” //这些值应该进入一个向量,(vectorOne)

vectorTwo //用于数据的子集标识符另一载体(vectorTwo)

“4”“5”“6” //这些值应进入一个不同的载体

vectorThree //标识符用于另一矢量数据的子集(vectorThree)

“7”“8”“9” //这些值应进入一个不同的载体


如果我寻找一个数据子集标识符/标签(如vectorOne),我只需要下一行的数据进入我的结果向量。问题是标识符/标签下的所有数据都在结果向量中结束。所以,如果vectorTwo是我想要的,我期望我的结果向量包含元素“4,5,6”。但这一翻译,它包含4至9在我的代码(如下图),我认为行:

while (file.get() != '\n'); 

确保读取将停止在一个换行符(即每一行数据后)。

对于出现什么问题,我将非常感激。

下面的代码(为了清楚起见,我将其配置为字符串):

#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& temp) 
{ 
    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 >> temp; 
       results.push_back(temp); 
      } 
      while (file.get() != '\n'); 
     } 
    } 
} 


int main() 
{ 
    const std::string theFile    = "test.txt"; // Path to file 
    const std::string findMe    = "labelInFile"; 
    std::string temp; 

    std::vector<string> results; 

    fileRead<std::string>(results, theFile, findMe, temp); 

    cout << "Result: \n"; 
    std::copy(results.begin(), results.end(), std::ostream_iterator<string>(std::cout, "\n")); 

    return 0; 
} 

感谢

回答

1

看起来像你对我可能有问题混合getlineget

当您阅读完所需矢量的名称后,即可开始阅读单引号之间的部分。一旦你阅读了单引号之间的任何内容,就检查下一个字符是否是行尾。如果换行之前还有其他内容,则测试失败,并且它读取下一对单引号之间的内容。如果在最后一个单引号之后的末尾或空格处有任何评论,您将会失败。

尝试将整行读入一个字符串,然后将其读取为一个字符串流。那样,你不能越过线的末尾。

+0

大卫,非常感谢!在我的外部文本文件中,我的行末没有任何评论,但我有一个空间!我摆脱了空间,现在代码按预期工作。我只是无法弄清楚为什么事情不起作用!非常感谢。 – user616199 2011-02-28 21:41:50