如何使用 c++ 逐行处理文本文件并将其参数拆分为变量?
How can I process a text file line by line and split it's parameters to variables using c++?
如果我有这样的文本文件:
- 阅读 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
拆分label
,opcode
和operand
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();
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 使用 C++ 将命令行参数拆分为参数/向量
- 在带括号的字符串中拆分参数
- Doxygen,当参数类型定义使签名相同时,如何拆分函数文档?
- 拆分参数包
- 根据函数指针参数拆分多个可变参数模板包
- 如何使用 c++ 逐行处理文本文件并将其参数拆分为变量?
- 在预处理器中拆分参数C++
- 如何在各个参数中拆分#__VA_ARGS__
- 按给定类型拆分参数包
- 拆分64位值以适应双精度参数类型
- 在c++ /Qt中拆分Lua函数调用的混合字符串/数字参数列表
- 取消对拆分函数调用参数的信任