从文本文件c ++中读取整数列

时间:2016-03-07 18:59:32

标签: c++

我正在尝试使用get line以这种格式从Exit 0文件中读取整数的"邮政编码列:

.txt

这是我到目前为止的相关部分:

Name|Address|Zipcode|DateOfBirth

但是,当我只想要邮政编码列时,这是在读取整个文件。

我如何只是&#34;抓住&#34; std::ifstream testfile; testfile.open("data.txt"); string zipcode; std::vector<int> inputVec; while(!testfile.eof()) { std::getline(testfile, zipcode, '|' ); // Need to store all zipcodes as ints in an array or vector // inputVec.push_back(zipcode); // trying to cout to screen to make sure its the right col. cout<<zipcode<<endl; // not working } 符号之间的那一列?

1 个答案:

答案 0 :(得分:0)

  

我如何“抓住”“|”之间的那一列符号?

文件中的文字记录:

Name|Address|Zipcode|DateOfBirth
    1       2       3

一种可能的方法(但抓住整条线,而不仅仅是列)

int t394(void)
{
   std::ifstream testfile;
   testfile.open("data.txt");

   std::string aTxtRecord;

   std::vector<std::string> inputVec;  // tbd - or integer

   do // read in whole file
   {
      // read entire line, one record at a time
      std::getline(testfile, aTxtRecord);

      if(testfile.eof())  break;  // completed

      // in the line, find one interesting '|', 
      //    perhaps the first after zip, last in the line
      size_t mrkr3 = aTxtRecord.rfind('|'); // last |
      if(mrkr3 == std::string::npos) // not found
      {
         //handle bad record - no marker in the string
         // set error code?  std::cerr << from here?
         break;  // file invalid, maybe should quite
      }
      // mrkr3 now points at the marker behind the Zipcode

      // find mrkr2 in front of the Zipcode
      // use find 2 times?  
      // use rfind 1 more time?  
      size_t mrkr2 = 0; // tbd

      // validate record - total mrkrs in line?

      // compute length of zip string i.e. mrkr3 - mrkr2 - 1?
      size_t length = mrkr3 - mrkr2;  // ? -1 or -2

      // now extract the Zipcode substring
      // compute how many chars in zipcode field 
      std::string zipcode = aTxtRecord.substr(mrkr2+1, // char after mrkr2
                                              length);  

      // store all zipcodes as strings (or tbd ints) in an array or vector
      inputVec.push_back(zipcode);

      // cout to screen for manual verification
      std::cout << zipcode << std::endl;

   } while(1);  // only exit is error or eof()

   testfile.close(); // possibly not needed

   // sort the vector

   return (0);
}