文件打开失败!从文件读取,C ++,xcode

File open failure! reading from a file, c++, xcode

本文关键字:文件 xcode 读取 失败      更新时间:2023-10-16

我在 c++ 问题中读取文件时遇到问题。请在下面找到我的代码并告诉我您的想法。我不断收到"文件打开失败!

问题:

编写一个程序,生成一个条形图,显示过去 100 年中每隔 20 年显示中西部小镇 Prairieville 的人口增长情况。该程序应从文件中读取1900年,1920年,1940年,1960年,1980年和2000年的人口数字(四舍五入到最接近的1000人)。 对于每年,它应显示日期和每 1000 人一个星号组成的条形图。例如,让我们使用 3000、7000、10000、25000、29000 和 30000。

下面是图表如何开始的示例:

普雷里维尔人口增长

(每个*代表1000人)

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 GROWTHn"  <<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;
}

从你提出的问题标签来看,我认为你正在使用Xcode,对吧?您需要知道 Xcode 将可执行文件输出到何处,并且您的 People.txt 文件需要放在与可执行文件相同的文件夹下。在 Xcode 中,转到

Xcode>偏好设置>位置

"派生数据"下显示的路径是 Xcode 放置可执行文件的位置。它通常是~/Library/Developer/Xcode/DerivedData。

在那里,您可能会找到很多项目的文件夹。进入与此项目对应的文件夹并转到构建/产品/调试,然后您将找到可执行文件。你能做的就是把你的人民.txt放在那里。

或者你可以将"People.txt"文件的完整路径添加到inputFile.open()方法中。

ifstream open() 在失败时设置 errno。因此,您可以获取其字符串表示形式以输出失败原因:

  cout << "File open failure:" << strerror(errno);

这篇文章非常有用 Xcode 新手 无法在 c++ 中打开文件? 该问题现已解决。原来该文件不在包含生成的可执行文件的文件夹中。谢谢:)