【问题标题】:Inserting info from a file into a struct将文件中的信息插入到结构中
【发布时间】:2016-04-20 22:04:06
【问题描述】:

我想从文件中提取数据并将它们存储到 myWorld 但我的 for 循环不起作用,程序一旦进入 for 循环就不会循环一次。我不确定问题是什么。这是我目前的代码。

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

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

const int MAXCOUNTRIES = 300;

struct World 
 {
  int     numCountries;
  Country countries[MAXCOUNTRIES];
 } myWorld;

void printPop ();

int main ()
{
 printPop();
 return 0;
}

void printPop()
{
 ifstream inFile("population.csv");

 if (!inFile.fail())
 {
    cout << "File has opened successfully.";
 }

 if (inFile.fail())
 {
  cout << "File has failed to open.";
  exit(1);
 }

 for (int i = 0; i < MAXCOUNTRIES; i++)
 {
    inFile >> myWorld.countries[i].pop1950 >> myWorld.countries[i].pop1970 >> myWorld.countries[i].pop1990
           >> myWorld.countries[i].pop2010 >> myWorld.countries[i].pop2015;
    getline (cin, myWorld.countries[i].name);
    cout << "loop is running" << endl;
 }

  inFile.close();
}

【问题讨论】:

    标签: c++ arrays file-io struct


    【解决方案1】:

    我认为你的循环正在运行,它只是在这里等待用户输入:

    getline (cin, myWorld.countries[i].name);
    

    【讨论】:

    • 谢谢!我通过更改该行来修复程序。
    • @H.C 当你有机会时,将其标记为答案。大卫得到了分数,未来的读者可以很容易地看到这确实是答案。
    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    相关资源
    最近更新 更多