I m writing a pice of code to read a txt file from the program directory and process the contet text for counting the word as a part of the functionality the user has to give the name of the text file that he placed in the program directory and if the file name is incorrect the program should ask again for the input. till the correct name is given. The piece fo code that i have written has no compilation errors but problem is at run time when the user give the wrong input then he is aked aging to give the correct in put but the while loop in the code doe nt terminate and keep on asking for the name even though the name is correct. I m using visual c++ express edition 2008.
I have used goto statement the code worked fine but using goto statement is not a good solution. So why the while loop does nt end
Here is the code for your reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
string input_file_name;
//xy:
cout << "Give the name of the file: ";
cin >> input_file_name;
ifstream input_file(input_file_name.c_str());
while(!input_file)
{
cout << "ERROR: opening the file failed" << endl;
// goto xy;
cout << "Give the name of the file: ";
cin >> input_file_name;
ifstream input_file(input_file_name.c_str());
}
string str = " ";
input_file >> str;
cout<<str;
@FeZedra (43)
your suggestion returns the following error while compilation@line (6) ie. {intput_file.open();}
" error C2661: 'std::basic_ifstream<_Elem,_Traits>::open' : no overloaded function takes 0 arguments"
Most progmming examples on this topic only display an error message and termite. but I havnt come across any coding example that ask for recreaton of the object if object creation failed. like e.g see.
i have tried withyour suggestion and it return no compilation error but at the run time the programm detects the fatal error crashes at the run time. i just wonder why the logic seems to be correct by why isnt it working.
Again, you are declaring a variable with the same name -> scope problem. (because of the clear the while loop ends, but the file is not open)
Just try to open the file