简体   繁体   English

C ++逗号分隔的Txt文件

[英]C++ Comma Delimited Txt File

I am working with my simple system that using .txt file as database in C++. 我正在使用简单的系统在C ++中使用.txt文件作为数据库。 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: 这是我的txt文件的示例:

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;

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

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