如何使用 c++ 逐行处理文本文件并将其参数拆分为变量?

How can I process a text file line by line and split it's parameters to variables using c++?

本文关键字:参数 拆分 变量 c++ 何使用 逐行 处理 文件 文本      更新时间:2023-10-16

如果我有这样的文本文件:

  • 阅读 RESW 1
  • TR RESW 10
  • LDA制造
  • 做字节 1

我尝试了这样的事情:

while (infile >> label >> opcode >> operand)

但问题是,当标签不存在时,就像在第 3 行那样,程序会等到它从下一行得到它的第三个参数。我该如何解决这个问题?

您可以读取行,然后从行中提取值。这样,如果最后一个参数不存在,您将不会从下一行读取:

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

int main()
{
    std::ifstream in("in.txt");
    std::string line;
    while (std::getline(in, line)) {
        std::string label;
        std::string opcode;
        std::string operand; 
        std::stringstream{ line } >> label >> opcode >> operand;
        std::cout << label << " " << opcode << " " << operand << std::endl;
    }
    return 0;
}

如果没有操作数,则operand字符串将为空。

你也可以这样做:

int operand = INT_MAX;
std::stringstream{ line } >> label >> opcode >> operand;
if(operand == INT_MAX) {
    // no int operand found
}

我建议您从文件中读取完整的行,然后使用strtok拆分labelopcodeoperand

string str;
ifstream myfile ("example.txt");
while ( getline (myfile,str) )
    {
        char *pch;
        pch = strtok (str," ");
        while (pch != NULL)
        {
          printf ("%st",pch);  // This will print the values which can also be stored in variables.
          pch = strtok (NULL, " ");
        }
    }
myfile.close();