In: Computer Science
Read and print parallel array - How can this be made to read parallel arrays and then print them?
The program presented here is intended to read from the text file and build parallel arrays. Then it will print as shown. The first line will not be stored in the array. The second line will be stored in firstArray[] and the third line will then be stored in secondArray[] and the arrays will repeat until the file is read.
begin external text file:
lineone
linetwo
line three
linefour
line five
begin program code:
ifstream infile;
string filname;
string line;
int i = 0;
cout << "Enter file name: ";
cin >> filname;
infile.open(filname.c_str());
getline(infile, line);
infile >> line; // first line
infile.ignore(20, '\n');
while (infile && i < 5)
{
i++;
getline(infile, firstArray[i]);
getline(infile, secondArray[i]);
}
string w;
string v;
w = firstArray[0];
v = secondArray[0];
cout << "*" << w << v << "*" <<
endl;
cout << "*" << firstArray[0] << "*" <<
endl;
cout << line << endl;
Here is the updated code, you didn't declared the arrays at the beginning also, I have assumed the size of the array to be5.
==========================================================================
#include<iostream>
#include<iomanip>
#include<string>
#include<fstream>
using namespace std;
int main(){
string firstArray[5];
string secondArray[5];
ifstream infile;
string filname;
string line;
int i = 0 , j = 0;
cout << "Enter file name: ";
cin >> filname;
infile.open(filname.c_str());
getline(infile, line);
while (getline(infile,line,'\n') &&i<5
&&j<5){
if((i+j)%2==0)
firstArray[i++]=line;
else
secondArray[j++]=line;
}
infile.close();
cout<<"First Array elements: \n";
for(int k= 0; k<i; k++)
cout<<firstArray[k]<<endl;
cout<<"Second Array elements: \n";
for(int k= 0; k<j; k++)
cout<<secondArray[k]<<endl;
return 0;
}
=================================================================
Output screenshot