Read and split with c++
用c ++我读了一个文件
1 2 | a;aa a;1 b;b bb;2 |
并使用此代码拆分行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #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); } |
但我在输出中得到了垃圾
1 2 3 4 5 6 7 | == 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?? |
为什么我会得到这个垃圾?
您对
也许输入文件不包含空行,但最后一次调用
我注意到的一个问题是你可能想要使用:
1 | results.push_back(str.substr(0, found - separator.length())); |
在