[英]storing word in a char array using getline is not working when used inside the loop?
[英]Using getline in loop, storing to an array
使用getline來存儲信息,我想有一個數組,使用'/'
作為分隔符,將整個列存儲在文本文件中,但是當創建循環通過第一行並將其存儲在a[i]
等等,然后移至下一行。
const int MAX = 20;
int main(){
string menuname;
string a[MAX];
string d[MAX];
string b[MAX];
string c[MAX];
string line;
bool error = false;
ifstream openFile;
int counter = 0;
do{
cout << "Please enter the name of the menu you would like to open: ";
cin >> menuname;
menuname += ".txt";
openFile.open(menuname.c_str());
if(openFile.fail()){
cerr << "Unable to open file, please re-enter the name.\n";
error = true;
}
//Determine how many lines long the text file is
while(getline(openFile, line)){
++counter;
}
//Testing the counter
cout << counter;
}while(error == true);
while(! openFile.eof()){
for(int i = 0; i < counter; i++){
getline( openFile, a[i], '/');
getline( openFile, b[i], '/');
getline( openFile, c[i], '/');
getline( openFile, d[i]);
}
}
for(int i = 0; i < counter; i++){
cout << a[i] << b[i];
}
}
當前,當我運行該程序時沒有錯誤,並且我僅顯示輸出即可測試計數器變量,該輸出正常工作,但是在程序的底部,我創建了一個小型測試,該測試應該打印一些2個數組我存儲了,但是什么也沒打印,並且程序在顯示計數器的值后才結束。
問題是當您實際存儲數據時,您位於文件的末尾。
while(getline(openFile, line)){
++counter;
}
從頭到尾讀取文件,然后在字符串上設置EOF標志。 然后你去
while(! openFile.eof()){
for(int i = 0; i < counter; i++){
getline( openFile, a[i], '/');
getline( openFile, b[i], '/');
getline( openFile, c[i], '/');
getline( openFile, d[i]);
}
}
並且由於設置了EOF標志,因此從不執行while循環。 由於您真正需要的是計數器,最后是顯示循環,因此我們可以將計數器循環和讀取循環合並為一個循環,例如
while(getline( openFile, a[counter], '/') && getline( openFile, b[counter], '/') &&
getline( openFile, c[counter], '/') && getline( openFile, d[counter])){
counter++;
}
現在,我們讀取了完整文件,並獲得了讀取的行數的計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.