为什么我的程序读取的不仅仅是我的txt文件的第一行?

Why is my program reading more than just the first line of my txt file?

本文关键字:我的 一行 文件 读取 程序 不仅仅是 txt 为什么      更新时间:2023-10-16

我在抓取textfile .txt的第一行时遇到了麻烦。我试过改变第二个参数中的数字并完全删除它。什么都没起作用,由于某种原因,我不能单独抓住1。

int main() {
ifstream fin; 
char ex1[100];
fin.open("txtfile.txt");
if (fin.is_open()) {
    cout << "YES FILE OPENED" << endl; //testing if file opened
}
while (fin.peek() != EOF){
    fin.getline(ex1, 100, 'n');
    cout << ex1 << endl;
    }
}

txtfile.txt:低于

1
ABC
2

如果只需要第一行,在获得第一行后从while循环中中断:

while (fin.peek() != EOF){
    fin.getline(ex1, 100, 'n');
    cout << ex1 << endl;
    break;
    }
}
    int main()
    {
       ifstream fin; 
       char ex1[100];
       fin.open("txtfile.txt");
       if (fin)
       {        
          while (!fin.eof())
          {
             fin.getline(ex1, 100, 'n');
             cout << ex1 << endl;
          }
          fin.close();
       }
     }