1

如果我在文本文件中有如下所示的行:

1    4:48:08   Orvar Steingrimsson                 1979   30 - 39 ara      IS200 
2    4:52:25   Gudni Pall Palsson                  1987   18 - 29 ara      IS870 

我怎样才能将此数据输出到一个新的文本文件中,但只列出三件事:年份 - 名称 - 时间......所以这两行看起来像这样:

1979   Orvar Steingrimsson   4:48:08
1987   Gudni Pall Palsson    4:52:25

我的猜测是这样的:

ifstream in("inputfile.txt");
ofstream out("outputfile.txt");
int score, year;
string name, time, group, team;
while (getline(in,str));
in >> score >> time >> name >> year >> group >> team;
//and then do something like this
out << year << name << time << '\n';

但是我有一种感觉,我无法在整个文本文件和所有 200 行中循环。任何提示表示赞赏!

4

2 回答 2

0

从上面的问题,我认为你需要用分隔符''或'\ t'分割文件。在 c++ 中,您可以使用 boost 库。在提升:

#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

using namespace std;

int main( int argc, char** argv )
{
  string s = "Hello, the beautiful world!";
  vector<string> rs;   // store the fields in your text.
  boost::split( rs, s, boost::is_any_of( " ,!" ), boost::token_compress_on );
  for( vector<string>::iterator it = rs.begin(); it != rs.end(); ++ it )
    cout << *it << endl;

  return 0;
}

或使用 strtok() 函数

#include <stdlib.h>    
#include <iostream>
#include <string.h>

using namespace std;

int main( int argc, char** argv )
{
  char str[] = "Hello, the beautiful world!";
  char spliter[] = " ,!";

  char * pch;
  pch = strtok( str, spliter );
  while( pch != NULL )
  {
    cout << pch << endl;
    pch = strtok( NULL, spliter );
  }
  return 0;
}

您也可以使用findorstrchr函数找到分隔符,然后您可以将其拆分。您可以yearvector<string> rs第一个样本或pch第二个样本中收到。

于 2013-09-27T01:29:00.390 回答
0

After you extract the substring, you can call strtol() (or std::stoi() if you have C++.11) to convert the string into an integer. Once you have both the year and the line of data, you can store them into some table, perhaps a std::multimap<>.

Without C++.11:

void process (std::istream &in, std::ostream &out) {
    typedef std::multimap<int, std::string> table_type;
    table_type data_by_year;
    std::string str;
    while (std::getline(in,str)) {
        int year = strtol(str.substr(54, 4).c_str(), 0, 10);
        data_by_year.insert(std::make_pair(year, str));
    }
    for (table_type::iterator i = data_by_year.begin();
         i != data_by_year.end();
         ++i) {
        out << i->second << "\n";
    }
}

In C++.11:

void process (std::istream &in, std::ostream &out) {
    std::multimap<int, std::string> data_by_year;
    std::string str;
    while (std::getline(in,str)) {
        int year = std::stoi(str.substr(54, 4));
        data_by_year.insert(std::make_pair(year, str));
    }
    for (auto v : data_by_year) {
        out << v.second << "\n";
    }
}
于 2013-09-26T23:48:38.417 回答