繁体   English   中英

C ++-如何从文件中获取字符串以另存为单独的字符串

[英]C++ - How to get strings from a file to be saved as separate strings

对此我有任何帮助,不胜感激。

对于这个项目,我们必须首先从文件中获取输入。 该文件如下所示:

----------------------------------------------------------------
Hi     Then  Finish
       End   Okay

----------------------------------------------------------------

Here is the layout for it:
Character Set 1: 1-6
Character Set 2: 7 (always a space)
Character Set 3: 8-11 
Character Set 4: 12-13 (always 2 spaces)
Character Set 5: 14-19

我想知道是否有一种方法来获取字符串中一定数量的字符。 每个字符集也将具有不同的变量。

例如:字符集1将被称为label ,字符集3将被称为code ,字符集5将被称为operation

我尝试了类似的东西

for (int i = 0; !text.eof(); i++){
   getline(text, label[i]);
   getline(text, code[i]);
   getline(text, operation[i]);
}

如果有帮助的话,现在这是我的代码...即使它不能正常工作:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main() {
  const int MAX     = 100;
  string    str;
  string    symLabel[MAX];
  string    opCode  [MAX];
  string    operand [MAX];

  ifstream sim("simprog.txt");

  for (int i = 0; !sim.eof(); i++){

    getline(sim, str);

    symLabel[i] = str.substr(0, 6);
    opCode[i]   = str.substr(8,11);
    operand[i]  = str.substr(13, 18);

    cout << symLabel[i] << endl;
    cout << opCode[i]   << endl;
  }
}

我将数组更改为rec的向量,其中rec是添加复制构造函数和operator =的字符串结构,以使其与STL容器兼容。 这不会将您限制为特定数量的输入行。 剩下的只是对代码的一些更改。

struct rec
{
    rec() { }
    rec(const rec &r) { *this = r; }
    rec &operator=(const rec &r)
    {
        if (this != &r)
        {
            symLabel = r.symLabel;
            opCode = r.opCode;
            operand = r.operand;
        }
        return *this;
    }
    std::string    symLabel;
    std::string    opCode;
    std::string    operand;
};

int main(int argc, char *argv[])
{
   std::string    str;
   std::vector<rec> records;

   std::ifstream sim("simprog.txt");

   char bf[100];
   while(sim.good())
   {
       sim.getline(bf, sizeof(bf));
       str = bf;

       rec r;
       r.symLabel = str.substr(0, 6);
       r.opCode   = str.substr(7, 5);
       r.operand  = str.substr(13, 6);

       records.push_back(r);
   }

   for (size_t i=0; i< records.size(); i++)
   {
       std::cout << records[i].symLabel << std::endl;
       std::cout << records[i].opCode   << std::endl;
   }

   return 0;
}

请注意,这需要您指定的格式正确的文件。 如果行格式更改,或最后一行不完整,您将遇到麻烦:)

暂无
暂无

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

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