ifstream does not work in loop
I just started programming using C++. I face some problem during execution of ifstream in loop.
do
{
system("cls");
inFile.open ("Account_Details.txt");
while (!inFile.eof())
{
开发者_Go百科 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.
Thanks for any help. ^^add infile.clear() after the infile.close() - the eof bits are not cleared by the close
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. During that time I have learnt how to use C++ in a way that minimizes the number of errors (bugs) I create. 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:
#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. Good luck with learning C++!
精彩评论