繁体   English   中英

C ++:从外部文件读取数据; 我的代码在文件结束前停止读取的问题

[英]C++: reading data from an external file; problem with my code for stopping read before end of file

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

该函数对于int / doubles似乎工作正常,但是我对字符串数据有问题。

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


vectorOne //一个向量的数据子集的标识符

'1''2''3'//这些值应进入一个向量(vectorOne)

vectorTwo //另一个向量(vectorTwo)的数据子集标识符

'4''5''6'//这些值应放入不同的向量

vectorThree //另一个向量(vectorThree)的数据子集标识符

'7''8''9'//这些值应放入不同的向量


如果我寻找数据子集标识符/标签(例如vectorOne),则只希望将下一行中的数据放入结果向量中。 问题在于,标识符/标签下的所有数据最终都在结果向量中。 因此,如果我想要vectorTwo,我希望我的结果向量包含元素“ 4、5、6”。 但是intead包含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;
}

谢谢

在我看来就像你可能有一个问题,混合getlineget

读取所需向量的名称后,就开始读取单引号之间的部分。 阅读完单引号之间的内容后,请检查下一个字符是否在行尾。 如果换行符之前的行还有其他内容,则测试将失败,并且它将读取下一对单引号之间的内容。 如果在行的末尾有注释,或者有空格,或者在最后一个单引号之后都没有任何内容,那么您所得到的将失败。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM