I am working with my simple system that using .txt file as database in C++. In my case, my code is working but the output is has too many repeats.. My system shows the list of name is the text file (second row in commas).
This is the sample of my txt file:
2015-1111,Christian Karl,M
2015-1112,Joshua Evans,M
2015-1115,Jean Chloe,F
2015-1113,Shairene Traxe,F
2015-1114,Paul Howard,M
And my desire output:
Christian Karl
Joshua Evans
Jean Chloe
Shairene Traxe
Paul Howard
Here is the problem.. It has many repeats.. My current output:
Christian Karl
Christian Karl
Christian Karl
Joshua Evans
Joshua Evans
Joshua Evans
Jean Chloe
Jean Chloe
Jean Chloe
Shairene Traxe
Shairene Traxe
Shairene Traxe
Paul Howard
Paul Howard
Paul Howard
I try to debug many times my code but seems nothing happen..
#include <string>
#include <vector>
#include <functional>
#include <iostream>
#include <fstream>
using namespace std;
void split(const string& s, char c,
vector<string>& v) {
string::size_type i = 0;
string::size_type j = s.find(c);
while (j != string::npos) {
v.push_back(s.substr(i, j-i));
i = ++j;
j = s.find(c, j);
if (j == string::npos)
v.push_back(s.substr(i, s.length( )));
}
}
int main( ) {
ifstream in("db.txt");
char str[255];
while(in) {
in.getline(str, 255); // delim defaults to '\n'
vector<string> v;
split(str, ',', v);
for (int i = 0; i < v.size( ); ++i) {
cout << v[1] << '\n';
}
}
system("pause");
return 0;
}
Anyone who can help me? Thanks!
Remove this
for (int i = 0; i < v.size( ); ++i) {
cout << v[1] << '\n';
}
and use this instead
if(v.size()>0){
cout << v[1] << '\n';
}
else{
break;
}
or better this
cout << v[1] << endl;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.