[英]Skip reading lines in a input file c++
所以我試圖將輸入文件讀入二維數組。
我遇到的問題是我只想讀取輸入文件中的某些行,但我只是不知道在我的代碼中將第二個忽略放在哪里
這是名為“Fruit.txt”的輸入文件:
Oroblanco Grapefruit
Winter
Grapefruit
Gold Nugget Mandarin
Summer
Mandarin
BraeBurn Apple
Winter
Apple
我的代碼:
#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();
}
我現在的代碼存儲如下:
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]
我希望它是這樣的:
Oroblanco Grapefruit // strAr[0][0]
Gold Nugget Mandarin // strAr[0][1]
BraeBurn Apple // strAr[0][2]
我只是不知道我應該把第二個忽略在哪里。 如果我在第一次忽略之后把它放好,那么它會超出我想要的范圍。
你的代碼很好,只需修復變量columnIndex
。
並使用3忽略因為你也需要忽略空行。
fin.ignore(10000,'\n');
fin.ignore(10000,'\n');
fin.ignore(10000,'\n');
您的代碼有幾個問題:
colIndex
是一個未使用的變量,也許是拼寫錯誤的問題; MAX_COL
應為3而不是4; rowIndex
, columnIndex
的順序錯誤。 代替
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++;
}
用這個:
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++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.