4

次のような .dat ファイルを読み取る必要があります。

Atask1 Atask2 Atask3 Atask4 Atask5
Btask1 Btask2 Btask3 Btask4 Btask5
Ctask1 Ctask2 Ctask3 Ctask4 Ctask5
Dtask1 Dtask2 Dtask3 Dtask4 Dtask5

そして、次のような情報を出力できる必要があります。

cout << line(3) << endl; // required output shown below
>>Ctask1 Ctask2 Ctask3 Ctask4 Ctask5

cout << line(2)(4) << endl; // required output shown below
>>Btask4

1 行を読み取って 5 つの異なる文字列の配列に分割する方法がわかりません。簡単に参照できるように、.dat ファイル全体をベクトル、リスト、またはある種の行列/配列構造に変換するのが理想的です。

これに対する簡単なコードまたは解決策はありますか??

助けてください?!?!?!?:-)

編集:

vector<string> dutyVec[5];

dut1.open(dutyFILE);

if( !dut1.is_open() ){
    cout << "Can't open file " << dutyFILE << endl;
    exit(1);
}

    if(dut1.eof()){
    cout << "Empty file - no duties" << endl;
            exit(1);
    }

while ( !dut1.eof()){
    int count = 0;
    getline(dut1, dutyVec[count]);
    count++;
}
4

1 に答える 1

4

あなたの問題は多くの問題に対処しています。それらすべてに一度に答えようとします。ということで、長文失礼します。

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <fstream>

int main(int argc, char argv[]){
  std::vector <std::string> v;//just a temporary string vector to store each line

  std::ifstream ifile;
  ifile.open("C://sample.txt");//this is the location of your text file (windows)

  //check to see that the file was opened correctly
  if(ifile.is_open()) { 
    //while the end of file character has not been read, do the following:
    while(!ifile.eof()) {
      std::string temp;//just a temporary string
      getline(ifile, temp);//this gets all the text up to the newline character
      v.push_back(temp);//add the line to the temporary string vector
    }
    ifile.close();//close the file
  }

  //this is the vector that will contain all the tokens that
  //can be accessed via tokens[line-number][[position-number]
  std::vector < std::vector<std::string> > tokens(v.size());//initialize it to be the size of the temporary string vector

  //iterate over the tokens vector and fill it with data
  for (int i=0; i<v.size(); i++) {
    //tokenize the string here:
    //by using an input stringstream
    //see here: http://stackoverflow.com/questions/5167625/splitting-a-c-stdstring-using-tokens-e-g
    std::istringstream f(v[i].c_str());

    std::string temp;

    while(std::getline(f, temp, ' ')) {
      tokens[i].push_back(temp);//now tokens is completely filled with all the information from the file
    }
  }
  //at this point, the tokens vector has been filled with the information
  //now you can actually use it like you wanted:
  //tokens[line-number][[position-number]

  //let's test it below:

  //let's see that the information is correct
  for (int i=0; i<tokens.size(); i++) {
    for(int j=0; j<tokens[i].size(); j++) {
      std::cout << tokens[i][j] << ' ';
    }
    std::cout << std::endl;
  }

  system("pause");//only true if you use windows. (shudder)
  return 0;
}

ここではイテレータを使用しなかったことに注意してください。しかし、それはあなたが自分で試みることができると思います。

于 2012-10-10T01:49:54.270 に答える