Problem with scanf in C

Thread Starter

Fraser_Integration

Joined Nov 28, 2009
142
Hi people. I hope my thread title is apt, I've got no idea why the following code won't work. Basically I want to take in 6 floating values and assign 4 in one array and 2 in a second, but they must be entered on one line and then the return key entered at the end. I would've thought that they would've just merrily waited for the six scanf calls to be put in place, but apparently not. If you run the code and type in, say, "1 2 3 4 5 6" then Enter, that is not what you end up with when I check with printf.

Can anyone see any glaring errors? Cheers.

Rich (BB code):
#include <stdio.h>

main()

{

float A[1][1];
float b[1];
float x1, x2;
int m = 0 , n = 0;

printf("Enter 6 values for matrix and answers.\n");

for (m=0;m<2;m++)
{
    for(n=0;n<2;n++)
    {               
       scanf("%f", &A[m][n]);
    }
}

for (m=0;m<2;m++)
{
    scanf("%f", &b[m]);
}

printf("%f   %f   %f   %f  %f  %f ", A[0][0], A[0][1], A[1][0], A[1][1], b[0], b[1]);

getchar();getchar();
}
 

Thread Starter

Fraser_Integration

Joined Nov 28, 2009
142
oh dont worry, I think I probably should've declared the arrays as [2][2] and [2] respectively, even though I only want to input to the [1][1] and [1] element, silly me
 

QuanSai

Joined Feb 14, 2010
1
Well, for what you want to do, you could use strtok() to break the input string into tokens. Each token can ten be stored as an element in each array. You could tokenize each floating-point number by indicating in your code that the delimiter is a space. Hence, in the string "12.2 24.4 48.8," token 1 would be 12.2, token 2 would be 24.4, and token 3 would be 48.8. You could then use something like strtod() or atof() to convert each tokenized string to a double. I'm not sure if that matters to you or not though.

I don't really know how much further you really want me to go with this.
 
Top