【问题标题】:Read and split with c++用 c++ 读取和拆分
【发布时间】:2012-01-02 16:13:00
【问题描述】:

使用 c++ 我读取一个文件

a;aa a;1 
b;b bb;2  

并使用此代码拆分行

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
vector<string> split(string str, string separator)
{
    int found;
    vector<string> results;
    found = str.find_first_of(separator);
    while(found != string::npos) {
        if(found > 0) {
            results.push_back(str.substr(0,found));
        }
        str = str.substr(found+1);
        found = str.find_first_of(separator);
    }
    if(str.length() > 0) {
        results.push_back(str);
    }
    return results;
}
void lectura()
{
    ifstream entrada;
    string linea;
    vector<string> lSeparada;
    cout << "== Entrada ==" << endl;
    entrada.open("entrada.in");
    if ( entrada.is_open() ) {
        while ( entrada.good() ) {
            getline(entrada,linea);
            cout << linea << endl;
            lSeparada = split(linea,";");
            cout << lSeparada[0] << endl;
        }
        entrada.close();
    }
    exit(0);
}

但我在输出中得到了垃圾

== Entrada ==
a;aa a;1
a
b;b bb;2
b

b a;11?E????aa a!(GXG10F????11?GXGb bb;21F????b bb!?G1?F????2??

为什么我会得到这个垃圾?

【问题讨论】:

标签: c++ split readfile


【解决方案1】:

您对getline 的最后一次呼叫将linea 留空。使用空行作为输入,split 将返回一个空向量(测试 length() &gt; 0 将为假)。尝试取消引用第一个元素 (lSeparada[0]) 然后调用未定义的行为。

也许输入文件不包含空行,但最后一次调用getline() 将失败。您应该使用while(getline(entrada,linea)) 而不是while(entrada.good()) getline(entrada,linea) 来测试std::getline() 返回的istream&amp; 是否良好。这可能会解决您的问题。

【讨论】:

    【解决方案2】:

    我注意到的一个问题是您可能想要使用:

    results.push_back(str.substr(0, found - separator.length()));
    

    split() 中,这样分隔符字符串就不会包含在您的输出中。

    【讨论】:

      猜你喜欢
      • 2014-10-22
      • 1970-01-01
      • 2016-06-02
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多