我想读取文件并将目标写入目标数组并将价格写入价格数组

时间:2016-05-11 08:31:19

标签: c++ arrays

我写了一个带有4个假日目的地的文件并且有价格,所以我想读取文件并将目的地写入目的地数组并将价格写入价格数组。文字格式就像

suncity 250
ushakamarue 300
krugerPark 450
Tablemountain 340

这就是我所拥有的

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

//define a constant for the number of lines to read 
#define NUM_READ_LINES 4
int main()
{

    // array of line numbers each line being less or equal to 100 chars

     char destination[NUM_READ_LINES][100];
     //string price[30];
     int counter = 0;
     //ofstream outfile;
     ofstream outfile("program.txt");
     if(outfile.is_open())
     {
         outfile <<"suncity 250\n ";
         outfile <<" ushakamarue 300\n";
         outfile <<" krugerPark 450\n";
         outfile <<" Tablemountain 340\n";
     }

     else 
       cout <<"Unable to open to file";

     outfile.close();

     //open a file
       ifstream infile;
       infile.open("program.txt");


      if(infile.good())
      {
        //Read throuh file and load into array
    while(!infile.eof() && (counter < NUM_READ_LINES))
    {
        infile.getline(destination[counter], 100);
        counter++;
    }
    //loop hrough the array which we just put together
    for (int i=0; i < counter;i++ )
        {
            cout << destination[i]<<endl;
        }
    }
    infile.close();


    return 0;
}

目前,该计划正在将整个太阳城250作为目的地阅读,而不是只将suncity读入目的地[1],将250只读入Price [1]。

1 个答案:

答案 0 :(得分:0)

这样的事情:

     string destination[NUM_READ_LINES];
     string price[NUM_READ_LINES];

     ifstream infile("program.txt");
     for (int ii = 0; ii < NUM_READ_LINES; ++ii) {
         infile >> destination[ii] >> price[ii];
     }