hello

I am reading a text file & trying to store some information into a 2d array.

My problem is when I go to store a piece of data into the 1st row (1d area ?:P) I get this error

error:

incompatible types in assignment of `float' to `float[25]'

For eg, I want to store 25.5 where x is
pur[x][];

My function:

float pur[53][25];   // Purchases Array [week number][purchase no.1, p2, pn...]

ifstream infile;
float x;
int count = 0; 
int count2 = 0;

while (infile >> x) {
           pur[count] = x;   // error occurs here
           
           while (x!=(char)'\n') {
                 pur[count][count2]= x;
                 count2++;
           }
           count2 = 0;
           count++;
     }

Dani AI

Generated

The core issues in this thread are twofold: assigning a single float to an entire row (the compiler error noted by ), and trying to detect line breaks by comparing numeric input to '\n' (which will not work because formatted extraction skips whitespace). and correctly pointed out that a 2D array needs both row and column indices, and 's suggestion to use vectors and line-based parsing is the right direction.

A reliable pattern: read the file line-by-line, split each line into tokens, treat the first token as the week (an integer) and the rest as purchase amounts (floats), then store those in a dynamic container. This avoids trying to detect newlines with numeric extraction and removes the need for manual atof/atoi conversions.

Example approach (keeps week->purchases flexible and safe):

#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <unordered_map>

std::ifstream infile("data.txt");
std::string line;
std::unordered_map<int, std::vector<float>> byWeek;

while (std::getline(infile, line)) {
    if (!line.empty() && line.back() == '\r') line.pop_back(); // handle CRLF
    std::istringstream iss(line);
    int week;
    if (!(iss >> week)) continue; // malformed line
    float amount;
    while (iss >> amount) byWeek[week].push_back(amount);
}

Practical tips and gotchas:

  • Use static_cast<int>(f) (or rounding helpers) when converting float to int; atoi expects a C-string and is not appropriate for floats.
  • If a fixed-size structure is required, use std::vector<std::vector<float>> with bounds checks and a clear policy for missing values.
  • Mixing operator>> and getline can leave stray newlines; prefer line-based parsing for record-oriented files.
  • Trim trailing \r when reading files from Windows hosts on other platforms.
  • Add simple checks (token count, value ranges) while parsing to detect corrupted lines early.

This pattern makes the code robust, easier to debug, and matches the file layout you described.

Recommended Answers

All 12 Replies

float pur[53][25];
// ...
pur[count] = x; // error occurs here

If pur[count] is an array of 25 floats, and x isn't, and you get an error, isn't that enough of a hint? You seem to know how to work it here:

pur[count][count2]= x;

Improper use of an array,

pur[count] = x; // Error

Try,

while (infile >> x) {
          if(count2==25) {
                count2=0;
                count++;
          }
      pur[count][count2]= x;
     count2++;
   }

Improper use of an array,

pur[count] = x; // Error

Try,

while (infile >> x) {
          if(count2==25) {
                count2=0;
                count++;
          }
      pur[count][count2]= x;
     count2++;
   }

oh, so are you saying that I cannot store 25.5 in where x is - pur[x][]? Is that not possible when I am using a 2d array?

so I cant cant go ...
cout << pur[x];
& it will output 25.5

>Is that not possible when I am using a 2d array?
Of course not. You're using a 2D array; you need a row AND a column.

Also, from experience. I see that using 2D array to store information
from a file does not always work well. The program might not set
the file content it to proper location. I would suggest to use 1D array.

If 2D is really needed , then use 1D array, and copy it into 2D array.

Thanks, lol, I realise now I can do this so I have changed it. But now I have run into another problem.

I am tring to convert x, which is a float into an int. but I get this error

cannot convert `float' to `const char*' for argument `1' to `int atoi(const char*)'

Is there a way I can fix this without changing x to a 'const char' or 'char', ie, keep it as a float.

while (infile >> x) {
           count = atoi(x);   // error occurs here again
           
           while (x!=(char)'\n' || count2<=25) {
                 pur[count][count2]= x;
                 count2++;
           }
           count2 = 0;
           count++;
     }

Also, from experience. I see that using 2D array to store information
from a file does not always work well. The program might not set
the file content it to proper location. I would suggest to use 1D array.

If 2D is really needed , then use 1D array, and copy it into 2D array.

Thanks :), I agree, 2d arrays are tedius, I wanted to test myself by using one(2d array) in a program but I dont really HAVE to use a 2d array. I am probably going to use a vector because it will be alot more efficient (memory-wise) & alot easier

" I am tring to convert x, which is a float into an int. but I get this error"

convert float to int :

float pi = 3.14159265;
int pie1 = pi; //implicit conversion from float to int
int pie2 = int(pi); //explicit conversion from float to int, C++ style //recommended
int pie3 = (int)pi; //explicit conversion from float to int, C style

you use atoi ( a string to int ). Converts a string to int.

int i = atoi("100");

Also atoi is not a good idea. Use the standard sstream header to convert between numbers to string vice-versa.

thanks guys

Although I am back again with a problem, I have totally overhauled the whole function but it still uses a 2d array.

In the below code, the variable 'count' is never advanced, ie, the if statement never gets called but it should whenever we get to a line break.

float x;

while (infile >> x) {

           if  (x==(char)'\n') {    // this event never happens but it should
                cout << "count advanced\n";
                count++;          
                pCount = 0;
           }    
           else {
                pur[count][pCount]= x;
                pCount++;
           } 
     }

The file I am reading is arranged like this

Week number purchase 1 purchase 2 purchase 3 purchase n

for eg.
1 2.4 1.4
32 1.4 2.7
50 8.45 2.56

cin does read spaces or newline. For spaces and new line
you should use the .get method.

As in

ifstream inFile("a.doc");
char c;

//this will show everything in file including newline and spaces
while( inFile.get(c) ) { cout << c<<endl;}

Yes sorry I am back again lol :P

Thanks for the help so far but yes I have changed, AGAIN :P, how I am doing it lol. I read firstPerson's reply & I am going to use his advice, use infile.get.

But I am back at the problem of changing a string/char to a float. How can I do this?

I cant really make x a char because remember I am reading float numbers from a text file, for eg;

layout = Week number - purchase 1 - purchase 2 - purchase 3 - purchase n

for eg.
1 2.4 1.4 // taking in fractional numbers
32 1.4 2.7
50 8.45 2.56

maybe I could make x a char array of 4 elements, char x[4] ??

So my major problems are:
- how to change x to a float (from a char array or string)
- how to take in number that are more than one character long(float numbers not ints) eg 12.04 using infile.get(char x))

string x;

while (infile.get(x)) {

           if  (x=='\n') {   
                cout << "count advanced\n";
                count++;          
                pCount = 0;
           }    
           else {
                pur[count][pCount]= x;  // here I need to change x from a char to a string if x is a char array of 4 elements does [B]atof[/B] still work??
                pCount++;
           } 
     }

This is handy for you :

Example :

#include<iostream>
#include<sstream>
#include<string>

using namespace std;

int main()
{
	stringstream ss;
	string myVal = "3.14159265";

	ss << myVal;

	float pi = 0;
	ss >> pi;
	cout<<"pi and pi*2 : ";
	cout<<pi <<"\t"<<pi*2<<endl;

	cout<<"\n\n";

	stringstream ss2;
	string myVal2 = "1.01 2.02 3.03";
	ss2 << myVal2;

	float val[3];
	int i = 0;
	while(ss2 >> val[i++])
		continue;

	cout<<"val contains : ";
	cout<<val[0]<<" "<<val[1]<<" "<<val[2]<<endl;
		

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.