Why did you start a new thread? Did you figure out the problem that @Ganado was trying to help you with?
The next question is, why do you bother asking the user to enter a file name if you don't use that name when you open the file? The user enters "file1" and you open "input1.txt". That doesn't really make sense.
I assume all of the input files will contain similarly formatted data. Instead of having separate blocks of code for input1.txt, input2.txt and input3.txt, you should have a single block of code (or even a function if you've learned how to use them) to do the work. Just pass in the chosen file name and do all of the common processing in a single place. You only need 1 input file stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
int main() {
int distance = 0;
string fileName = " ";
string inputStreamName = " ";
do {
cout << "Please enter a file name." << endl;
getline(cin, fileName);
} while (fileName != "file1"&& fileName != "file2"&& fileName != "file3");
cout << "Reading File... Done" << endl; // huh? you haven't read the file yet!
if (fileName == "file1")
{
inputStreamName = "input1.txt";
}
else if (fileName == "file2")
{
inputStreamName = "input2.txt";
}
else if
{
inputStreamName = "input3.txt";
}
// This should be code common to all input files!!
ifstream input;
input.open(inputStreamName);
string line;
int x1;
int x2;
int y2;
int y1;
input >> x1 >> x2 >> y1 >> y2;
if (input.is_open()) {
while (getline(input, line)) {
cout << line << endl;
}
// etc.
| |
However, to make sure you have things working, start by hard-coding the file name to one of the data files. Leave the user interface until you have the guts of the program working. In other words, comment out lines 5-26 (of my code) and replace them with
string inputStreamName = "input1.txt";
Get your code working and then add in the ability to choose the input file.
Some hints. Your distance will need to be a floating point number -- I recommend a
double
.
Start by simply reading in a line and writing it back out. In line 36 (of your code) you read in a line (in piecemeal fashion) and don't do anything with it. Then in lines 38 and 39 you read in the entire file line by line and print out each line except the first, which was read in line 36. Lines 42-45 also seem to be what you want, but you've already exhausted your file, so there is nothing left to read.
Figure out what you are trying to do. Simplify your code to do 1 thing at a time, and add on a new capability only after the previous step works.