1

I am having an issue reading from a file in a c++ problem. Please find my code below and tell me what you think. I keep on getting "File open failure!"

Problem:

Write a program that produces a bar chart showing the population growth of Prairieville, a small town in the Midwest, at 20 year intervals during the past 100 years. The program should read in the population figures (rounded tot he nearest 1000 people) for 1900, 1920, 1940, 1960, 1980 and 2000 from a file. For each year it should display the date and a bar consisting of one asterisk for each 1000 people. For example, let's use 3000, 7000,10000, 25000, 29000 and 30000.

Here is an example of how the chart might begin:

PRAIRIEVILLE POPULATION GROWTH

(each * represents 1000 people)

1900 ***

1920 *******

1940 **********

//  main.cpp
//  Population Chart

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  int year,population;
  ifstream inputFile;
  inputFile.open("People.txt");
  //if (inputFile.fail())
  if(!inputFile)
    {
        cout << "File open failure!";
    }

  cout << "PRAIRIEVILLE POPULATION GROWTH\n"  <<endl;
  cout << "(each * represents 1000 people)\n" <<endl;

  while (inputFile >> population)
  {
        for (year =1900 ; year<=2020; year += 20)
        {
            cout<< year;
            for (int i = 1; i <= population/1000; i++)
            {
                cout<<"*";
            }
            cout<< endl;
        }
  }

  inputFile.close();

  return 0;
}
ab_dev
  • 93
  • 8

3 Answers3

0

From the tag you put to the question, I think you are using Xcode, right? You need to know where does Xcode output the executable, and your People.txt file needs to be put under the same folder as the executable. In Xcode, goto

Xcode > Preference > Locations

The path shown under "Derived Data", is where Xcode put executable. It's typically ~/Library/Developer/Xcode/DerivedData.

There you will probably find a lot of folders of your projects. Go into the folder corresponds to this project and goto Build/Products/Debug, then you will find your executable. What you can do is put your People.txt there.

OR your can add the full path of your "People.txt" file to your inputFile.open() method.

Da Teng
  • 551
  • 4
  • 21
  • Thanks alot! that was very useful. Yeah! It worked after i put the People.txt in the folder with the executable. appreciate it – ab_dev May 24 '16 at 05:12
0

ifstream open() sets errno on failure. So you may obtain its string representation to output the reason of failure:

  cout << "File open failure:" << strerror(errno);
Mikhail Volskiy
  • 209
  • 2
  • 5
0

This post was very useful New to Xcode can't open files in c++? the issue is now resolved. Turns out the file was not in the folder containing the generated executable. Thanks :)

Community
  • 1
  • 1
ab_dev
  • 93
  • 8
  • that too was useful https://github.com/jsquared21/StartingOutCPP/blob/master/PC_5/PC_5_23.cpp – ab_dev May 24 '16 at 07:17