Read float data from txt file to array

I've got a data file where each row has a float with two decimal precision, where each row represents a month, and there are 28 years worth of data. I'm trying to read in each line, and then store each line in an array. Then, using user input, store the data for a specific year inside a smaller array.

Here's what I've got so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;

int main()
{
ifstream derp ("co2data.txt");
int year,i=0,variable,current_year;
float month_avg[12];
char alldata[336];
  for (i=0;i<336;i++)
	{
	alldata[i]=0;
	}
  for (i=0;i<12;i++)
	{
	month_avg[i]=0;
	}

   for(i=0;i<336;i++)
      {
	 derp.getline(alldata[i], 100);
      }


cout << "Year: "<< endl;
cin >> current_year;
year=(current_year-1980)*12;
cout << year << endl;

for(i=0;i<12;i++)
      {
         month_avg[i]=alldata[year+i];
      }
   for(i=0;i<12;i++)
      {
         cout << month_avg[i] << endl;
      }

}


When I compile this, I receive the following error:

1
2
3
4
g++ -o test.out test.cpp
test.cpp: In function ?int main()?:
test.cpp:23: error: invalid conversion from ?char? to ?char*?
test.cpp:23: error:   initializing argument 1 of ?std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::getline(_CharT*, std::streamsize) [with _CharT = char, _Traits = std::char_traits<char>]?


What am I doing wrong? Is there an easier way to accomplish this?
Thanks!
I can tell you what the problem is - cin.getline() takes a char* (C-string) and you are passing alldata[i], which is just a single character. Personally, I would read each bit of data into a string (to avoid the work of C-strings) and parse it into floats that way.
Okay, I made all data an array of characters, and used atof to convert it back to a float, but now it the program returns a constant value of 3.4e+02 for all 12 data points.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <iomanip>
#include <cstring>
#include <fstream>
#include <stdlib.h>
#include <string.h>
using namespace std;

int main()
{
ifstream derp ("co2data.txt");
int year,i=0,variable,current_year;
float month_avg[12];
char alldata[336][100];
  for (i=0;i<12;i++)
	{
	month_avg[i]=0;
	}

   for(i=0;i<336;i++)
      {
	 derp.getline(alldata[i], 100);
      }


cout << "Year: "<< endl;
cin >> current_year;
year=(current_year-1980)*12;
cout << year << endl;

for(i=0;i<12;i++)
      {
         month_avg[i]=atof(alldata[year+i]);
      }
   for(i=0;i<12;i++)
      {
         cout <<month_avg[i] << endl;
      }

}
Nevermind; it seems to be working now!
Last edited on
Topic archived. No new replies allowed.