如何在特定位置之前/之后从文本文件中读取输入 [C++]? [英] How to read input from the text file until/after a specific location [C++]?
问题描述
在我的项目中,我需要从文本文件中获取有关电路的数据,然后我需要解析它并生成输出数据.这是文本文件的示例数据
In my Project I need to get data about circuit from a text file then I need to parse it and produce to output data. Here is a sample data for the text file
AND1 Adder1-3 Adder1-4//表示 AND1 门从Adder1 的第 3 个输出和 Adder1 的第 4 个输出的第二个输入
AND1 Adder1-3 Adder1-4 // Means AND1 gate gets its first input from Adder1's 3rd output and its second input from Adder1's 4th output
AND2 Adder1-4 Adder1-2
AND2 Adder1-4 Adder1-2
OR1 AND1-1 AND2-1//OR1的两个输入来自AND1的第一个输出和AND2的第一个输出
OR1 AND1-1 AND2-1 //OR1's two inputs are from AND1's 1st output and AND2's 1st output
现在我需要先读取组件名称,这很容易:
now I need to read the component name first which is easy:
infile>>componentName;
但是对于第二部分,我认为我可以通过多种方式进行
But for the second part I though I could to this in to ways
- 读取整个数据并将其分成两部分: ComponentName -输出.
- 读取直到-"并将其放入字符串变量然后读取在-"之后并将其放入整数变量并对所有重复此操作线.
我尝试了第一种方法,但我真的坚持将字符串转换为整数(我尝试使用 stoi 但它仅用于 C++ :( 并且还遇到了几个问题)但我虽然第二种方法会更容易,但我不能不知道该怎么做.
I tried the first way but I really stuck at converting string into integer (I tried using stoi but its for C++ only :( and also encountered with couple of problems) but I though the second way would be much easier but I couldn't figure it how to do it.
你能帮我解决这个问题吗?基本上我需要将组件名称(在-"之前)放入字符串变量并将整数(在-"之后)放入整数变量.
So can you help me with this ? Basicly I need to put component name(before "-") into string variable and put the integer (after "-") into integer variable.
注意:对不起,我的英语不好,不是母语人士.由于项目很大,我没有在上面放不必要的代码.
NOTE: Sorry for my poor English not a Native Speaker. and since the Project is large I didn't put unnecessary codes above.
推荐答案
这是相当基本的,但应该可以帮助您入门.对于这些任务,我更喜欢 scanf
系列.
This is rather basic, but should get you started. I prefer the scanf
family for these tasks.
#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
FILE *fp=fopen("tmpfile", "r");
char oper[5], dev1[10], dev2[10];
int op1, op2;
fscanf(fp, "%s %[^-]-%d %[^-]-%d", oper, dev1, &op1, dev2, &op2);
cout<<oper<<endl;
cout<<dev1<<endl;
cout<<op1<<endl;
cout<<dev1<<endl;
cout<<op2<<endl;
fclose(fp);
}
为 AND2 Adder1-4 Adder1-2
产生的输出:
AND2
Adder1
4
Adder1
2
这篇关于如何在特定位置之前/之后从文本文件中读取输入 [C++]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!