1.Container ID.txt
Container Type: Refrigerated_Explosive //Enter one serial no. per line
1990
1991
1992
END RE
This is my input file for a c++ program. My objective here is to read all the lines between the lines containing 'Refrigerated_Explosive' and 'RE' (ie I want to read the numbers 1990, 1991, 1992 in this case)
So far I've tried to store the second word in each line to a string variable using 'while(file1>>value>>type)' and compare it with 'Refrigerated_Explosive', if both are equal move to next line and read the content (and store in a different file) until second word is 'RE'.
#include<iostream>
#include<conio.h>
#include<string>
#include<fstream>
using namespace std;
int main()
{
ifstream file1;
ofstream file2;
int value;
string type;
file1.open("1.Container ID.txt"); //Input File
if(file1)
{
file2.open("1.CID.txt"); //Output File
while(file1>>value>>type)
{
if(type == "Refrigerated_Explosive") //If equal read from next line
{
while(file1>>value>>type)
{
if(type != "RE") //Read until 'RE' not found
file2<<value<<endl;
}
}
}
}
else
cout<<"Source File not Found1!!!\n";
file1.close();
file2.close();
return 0;
}
You can use getline()
function to read a line, getline()
stops reading if it meet new line character \\n
.
#include<iostream>
#include<conio.h>
#include<string>
#include<fstream>
using namespace std;
int main()
{
ifstream file1;
ofstream file2;
file1.open("input.txt"); //Input File
file2.open("output.txt"); //output file
string line;
while(getline(file1,line))
{
//if the line contains "Refrigerated_Explosive" then read number until meet RE
if(contains(line,"Refrigerated_Explosive"))
{
string number;
while(getline(file1,number)) //read number and write to file output
{
if(number!="RE")
{
file2<<number<<"\n";
}
else return 0; //break if meet "RE"
}
}
}
file1.close();
file2.close();
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.