简体   繁体   English

ifstream不能循环工作

[英]ifstream does not work in loop

I just started programming using C++. 我刚刚开始使用C ++进行编程。 I face some problem during execution of ifstream in loop. 在循环执行ifstream期间遇到一些问题。

do  
{  
    system("cls");  
    inFile.open ("Account_Details.txt");  
    while (!inFile.eof())  
    {  
         getline (inFile, line);  
         cout << line << endl;  
    }  
         inFile.close();  
         cin.ignore(100, '\n');  
         cin >> choice;  
}  
while (choice != '1' && choice != '2');  

This is part of my code. 这是我的代码的一部分。 When the loop run, it doesnt show data in the txt file. 循环运行时,它不会在txt文件中显示数据。
Thanks for any help. 谢谢你的帮助。 ^^ ^^

在infile.close()之后添加infile.clear()-关闭不会清除eof位

There is a chance that the file doesn't exist. 该文件可能不存在。 If that's the case, it will create an empty file. 如果是这样,它将创建一个空文件。 Check the path of the file. 检查文件的路径。

I have been writing C++ code for close to 10 years. 我一直在编写C ++代码已有近10年的时间。 During that time I have learnt how to use C++ in a way that minimizes the number of errors (bugs) I create. 在这段时间里,我学习了如何以最小化我创建的错误(bug)数量的方式使用C ++。 Probably some will disagree with me, but I would recommend you to only use for and while to do looping. 可能有些人会不同意我的观点,但我建议您仅在进行循环时使用。 Never do-while. 永远不要做。 Learn these two well and you will be able to loop successfully any time you want. 很好地学习这两点,您将可以在任何时间成功循环。

To illustrate my technique, I have taken the liberty to rewrite your code using my style. 为了说明我的技术,我随意使用我的样式重写您的代码。 It has complete error checking, uses a while loop with read-ahead, some C++0x, and simplified stream handling: 它具有完整的错误检查功能,使用带有预读功能的while循环,某些C ++ 0x和简化的流处理:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

int main(int argc, char** argv)
{
   // check program arguments
   if (argc<2) {
      std::cerr << "Usage: " << argv[0] << " file" << std::endl;
      return EXIT_FAILURE;
   }

   // check file can be opened
   std::ifstream infile(argv[1]);
   if (!infile) {
      std::cerr << "Failed to read " << argv[1] << std::endl;
      return EXIT_FAILURE;
   }

   std::string input;

   // read-ahead
   std::getline(std::cin, input);

   while (input!="q" && input!="quit" && input!="exit") {
      //system("cls");

      // print contents of file by streaming its read buffer
      std::cout << infile.rdbuf();

      // read file again
      infile = std::ifstream(argv[1]);

      // finally, read again to match read-ahead
      std::getline(std::cin, input);
   }
}

Save to main.cpp , compile to print.exe and run with print.exe main.cpp . 保存到main.cpp ,编译为print.exe并使用print.exe main.cpp运行。 Good luck with learning C++! 学习C ++祝您好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM