0

要使用我编写的代码来执行计算,我需要从外部文本文件中读取数据(数字和字符串)并将它们存储在字符串或整数/双精度的向量中。我为此编写了一个模板函数。CashCow、Howard Hinnant 和 wilhelmtell 帮助解决了之前的问题。

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

我需要来自外部文件的一行的数据进入向量,但函数读取多行。这就是我的意思。假设这是外部文本文件中的内容(如下):


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;
}

谢谢

4

1 回答 1

1

在我看来,您可能在混合getlineget.

当您阅读了所需矢量的名称后,您开始阅读单引号之间的部分。一旦您阅读了单引号之间的内容,您就可以检查下一个字符是否是行尾。如果换行符之前的行上还有其他内容,则测试失败并读取下一对单引号之间的内容。如果行尾有注释,或者空格,或者最后一个单引号之后的任何内容,那么你所得到的将会失败。

尝试将整行读入字符串,然后将其作为字符串流读取。这样,您就不能越过行尾。

于 2011-02-28T21:32:20.660 回答