Modyfing a char table within a loop to display "x = i"

Hello,
I need help writing a simple loop that would change the size of char table (I need it to be the exact size as text plus one space for 0 that ends the table).

I need the loop to modify the table so that is displays "x = i" where i would be increased by 0.1 or 0.01 each time it loops.

The output would be:
x = 0.0 (or just 0)
x = 0.1
x = 0.2
...
x = 50.0

Can you help me with this one?

Cheers,
Luke
At the moment I have something like that, but it only produces numbers up to 9.9, how could I expand it so it does that until like 50. What's more, at 7.9 it also displays some random letters, why is that?


Unfortunately char is the only way to go here, because that's how I need my data to be stored.

#include<iostream>

using namespace std;

int main(){
int length;

for (int i=0;i<10;i++){
for (int j=0;j<10;j++){
length = 5;
char* s = new char[length];
s[0]='x';
s[1]='=';
s[2]=i+48;
s[3]='.';
s[4]=j+48;
cout<<s<<endl;
}
}
}
The array is too small, "x=0.0" requires six characters, "x=50.0" would require seven - allowing for the null terminator. You are getting random characters because you forgot to either allow space for the null terminator, or to place that terminator in the array.

Also, using new here seems unnecessary. It also gives a memory leak as none of the allocated arrays is ever deleted.

You could define the table at the start since you know its dimensions.
1
2
    const int SIZE = 501;
    char table[SIZE][7];

or use a c++ std::string,
 
    string table2[SIZE];


In order to put those values into it, perhaps the easiest way would be to use sprintf or a c++ ostringstream, either of which would avoid having to fiddle with i+48 etc.

Last edited on
Topic archived. No new replies allowed.