【发布时间】: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??
为什么我会得到这个垃圾?
【问题讨论】:
-
尝试在 valgrind 下运行程序以查找内存访问错误。
-
为了更简单的分割方式';'看看stackoverflow.com/questions/5167625/…