im having trouble opening a file,and checking to see if it was opend correctly..the user is supposded to enter the name of the file which contains a list of intergers.my do..while loop isnt looping and i cant figure out how to fix it also..eventualy i want to store the numbers in the file in an array and do calculations..
I don't think you interpret it quite correctly. Your function openfile is intended to get a filepath, check if it's valid, and if it isn't, get another path. (Right?) In that case, your error response, which is outside the loop, should be in it. In addition, is_open() returns true if a file is connected to the stream. You only want the loop to repeat if the file is invalid, but you currently have it repeating as long as the file is valid. Therefore the condition should be while(!infile.is_open()).
You know how to use an ifstream right? You'd just do something like this: infile >> num;
The operator would then read in as many valid numbers as it could. You'd store that in an array and keep reading numbers out of the stream until you hit eof.
That's because you're basically doing this:
1. Ask the user to enter the name of the input file
2. Read the input file's name
3. Open the input file
4. If input file is open, goto 1
else tell the user it's not valid and return
I think you mean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int openfile(std::ifstream& infile)
{
std::string infileName;
int i = 0;
while (!(infile.is_open()) {
if (i++ > 0)
std::cout << "Invalid file, or no such file \"" << infileName << "\"\n";
std::cout << "Enter the name of the input file: "; /* You don't need std::endl here; */
std::getline(std::cin, infileName); /* You should use std::getline() for strings */
infile.open(infileName.c_str());
}
return (int)infile.is_open();
}
Note: I use std:: here because I like to; but you don't have to.
I would also like to mention that your indentation is a little inconsistant and messy. Perhaps you could clean it up a little.
I think that, for a relative path, you need \input1.txt, not just input1.txt (which searches the root of the drive IIRC). helios corrected me on this once, search the forums.