Skip read lines in c ++ input file
So I am trying to read an input file into a two dimensional array.
The problem I'm running into is that I only want to read certain lines in my input file, but I just don't know where to put the second ignore in my code
Here is an input file named "Fruit.txt":
Oroblanco Grapefruit
Winter
Grapefruit
Gold Nugget Mandarin
Summer
Mandarin
BraeBurn Apple
Winter
Apple
And my code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
const int MAX_ROW = 6;
const int MAX_COL = 4;
void FileInput(string strAr[MAX_ROW][MAX_COL])
{
ifstream fin;
fin.open("Fruit.txt");
int columnIndex;
int rowIndex;
rowIndex = 0;
while(fin && rowIndex < MAX_ROW)
{
columnIndex = 0;
while(fin && columnIndex < MAX_COL)
{
getline(fin, strAr[rowIndex][columnIndex]);
fin.ignore(10000,'\n');
columnIndex++;
}
rowIndex++;
}
fin.close();
}
My code now saves it like this:
Oroblanco Grapefruit // strAr[0][0]
Grapefruit // strAr[0][1]
Gold Nugget Mandarin // strAr[0][2]
Mandarin // strAr[0][3]
BraeBurn Apple // strAr[1][0]
Apple // strAr[1][1]
I want it to be like this:
Oroblanco Grapefruit // strAr[0][0]
Gold Nugget Mandarin // strAr[0][1]
BraeBurn Apple // strAr[0][2]
I just don't know where I should place the second ignore. If I put this right after the first ignore then it will miss more than I want.
+3
source to share
2 answers
There are several problems in your code:
-
colIndex
- unused variable, possibly a problem with typos; -
MAX_COL
must be 3 not 4; - The order
rowIndex
iscolumnIndex
wrong.
Instead
const int MAX_COL = 4;
while(fin && rowIndex < MAX_ROW)
{
colIndex = 0; // unused variable
while(fin && columnIndex < MAX_COL) // MAX_COL should be 3
{
getline(fin, strAr[rowIndex][columnIndex]); // order problem
fin.ignore(10000,'\n');
columnIndex++;
}
rowIndex++;
}
use this:
const int MAX_COL = 3; // MAX_COL should be 3
while(fin && rowIndex < MAX_ROW)
{
columnIndex = 0; // variable name fixed.
while(fin && columnIndex < MAX_COL)
{
getline(fin, strAr[columnIndex][rowIndex]); // order matters
if (strAr[columnIndex][rowIndex].empty() == false ||
no_need_to_ignore()) { // your sikp logic added here
columnIndex++;
}
}
rowIndex++;
}
+2
source to share