通过 Sublime Text 命令面板正确操作 CSV 文件输出的 C++ 代码...但不是在终端中

C++ Code that manipulates CSV file outputs correctly via Sublime Text Command Palette...but not in Terminal

在我最近的实验室中,我被分配了一项相当基本的任务 - 获取包含人口数据的 CSV 文件并输出各种详细信息,例如人口最多的国家/地区。为了简洁起见,我在下面包含了我的代码的截断版本:

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

  struct Country {
    string name;
    double pop1950;
    double pop1970;
    double pop1990;
    double pop2010;
    double pop2015;
  };

  struct World {
    int numCountries;
    Country countries[229]; // plugged this value with the number of countries from the CSV file. 
  } myWorld;

  int main()
  {
     ifstream csvStream; 
     csvStream.open ("population.csv");

        double vpop1950;
        double vpop1970;
        double vpop1990;
        double vpop2010;
        double vpop2015;
        string conName;

        int counter = 0; 


       while (csvStream >> vpop1950 >> vpop1970 >> vpop1990 >> vpop2010 >> vpop2015) 
       {
        getline(csvStream, conName);
        // instantiate a country structure per line. 

        myWorld.countries[counter].name = conName; 
        myWorld.countries[counter].pop1950 = vpop1950; 
        myWorld.countries[counter].pop1970 = vpop1970;
        myWorld.countries[counter].pop1990 = vpop1990; 
        myWorld.countries[counter].pop2010 = vpop2010;
        myWorld.countries[counter].pop2015 = vpop2015; 
        counter++;

        // cout << conName << endl; 
       }

       // For task 2, where are going to get the top 3 countries. Let's start with the top country, and repeat the loop below 2 more times.

       // Figure out the biggest population.
       double placeVal = myWorld.countries[0].pop2015; // use this to compare and store the top 100 
       string topCon = " ";

       for (int i = 0; i < 229; i++)
       {
        if (placeVal < myWorld.countries[i].pop2015)
        {
            placeVal = myWorld.countries[i].pop2015;
            topCon = myWorld.countries[i].name;
        }
       }

       cout << "The largest country is" << topCon << " which had " << placeVal * 1000 << " people in 2015." << endl; // Multiplied by 1000 as per lab instructions. 

     return 0;

     csvStream.close();

  }

当我在 sublime text 中键入 Command+Shift+B 并编译并执行文件时,我得到以下输出:

The largest country is China
 which had 1.37605e+09 people in 2015.
[Finished in 0.3s]

在终端中执行相同的可执行文件,我得到以下信息(在 mac 和 ubuntu 上):

The largest country is  which had 0 people in 2015.

我的实际代码要长一些,我在我的程序的原始版本中执行了各种其他计算,但同​​样的错误仍然存​​在 - 输出显示在 sublime 文本中,而不是在实际终端中。有什么想法吗?

您的程序假定 population.csv 在当前工作目录中。如果当前目录不包含该文件,则无法读入该文件。

SublimeText 很可能在执行程序时将当前目录设置为该程序所在的目录。

当运行从终端发出命令时,执行的程序会从终端继承当前目录。例如,如果你的程序在 ~/src/my_program 中,但终端中的当前目录是你的主目录,那么你程序的当前目录将是你的主目录,而不是 ~/src/my_program.

如果你将终端中的当前目录更改为你程序所在的目录,那么应该可以正确读取文件。