James Rnep Jacobs
James Rnep Jacobs

Reputation: 21

Trouble reading .txt file

Hello all I am a very basic programmer and am trying to learn how to make my code read a .txt file but it won't have anything pop up when I try to compile it nothing happens. I get the obvious errors for not using my double values but the .txt file i input with my .cpp file should print a result to the screen. The premise of this project is to write a program that reads in from a file two month names followed by the rainfall amounts(Rainfall.txt) for each month in that span of months. The program should calculate the totals and output the average for each month. I'm very confused why this is not working and would love some constructive and hasty feedback thank you for considering and taking your time.

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

using namespace std;
int main()

{
string months_one, months_two;
double total=0, average=0;
int counter;

ifstream myfile;
myfile.open("Rainfall.txt");

if ( myfile.fail())
{
    cout << "Error on file open." << endl;
}
else
{
    myfile >> months_one;
    myfile >> months_two;


    }
    cout << months_one << months_two;
    }

Upvotes: 1

Views: 787

Answers (2)

Kyle H
Kyle H

Reputation: 921

I just had this very same problem. What I was doing wrong was taking .txt files from a location on my computer and dragging them into my C++ project in Eclipse. The problem was that even though they appeared to be in my "workspace" that actually were not. I had to go /usr/home/workspace (The location of your code may be different) From there, find the project folder you are working on and put you .txt files in there. Then go back to your project in Eclipse, right-click, and "Refresh" your project.

From there the files should appear and your program should run properly.

Upvotes: 0

Grizz
Grizz

Reputation: 320

I'm not quite sure what you're asking here... I ran a quick test copying your code as is and it outputs (albeit a bit oddly) two lines of a text file...

When you say "when I try to compile it nothing happens"... you mean you try to compile it and it does not build the binary?

I wonder if you may be running the program, perhaps by double-clicking on the resulting binary, and the command prompt is popping up and going away before you can even see it? See maybe this question.

Edit: Ooops actually maybe this question is better...

Upvotes: 1

Related Questions