Thread: 2d array input

1. 2d array input

hi there. having some problems reading in a 2d array by column, then row. i'm programming simple dos-type "console application" programs. i'm not sure how to input the data eg. how many spaces between each array element, and the code i've got below doesn't generate the required output.
here's what i got so far: (any ideas appreciated)

Code:
```#include <stdio.h>
#include <conio.h>
#include <string.h>

main()

{
int i, j, bus[4][5];

for(j = 0; j <= 5; j = j + 1)
}
for(i = 0; i <=4; i = i + 1)
scanf(" %d", &bus[i][j]);

{

for(j = 0; j <= 5; j = j + 1)

printf("Give the number of passengers for day 1: bus[i][0]");
printf("Give the number of passengers for day 2: bus[i][1]");
printf("Give the number of passengers for day 3: bus[i][2]");
printf("Give the number of passengers for day 4: bus[i][3]");
printf("Give the number of passengers for day 5: bus[i][4]");

getch();

}```
2d array by column, then row

2. Spaces are irrelevant. However, you do want to be sure you don't go out of yoru boundries:

for(j = 0; j <= 5; j = j + 1)

You don't want this to ever equal 5. You want:

for( j=0; j<5; j++ )

Because otherwise:

array[x][5] is invalid.

Remember, arrays only go from zero to size-1. So your valid array elements are from 0 to 4. If your counter equals 5 and you try reading input, you'll have problems.

Quzah.

3. Ur reply

OK, thanx a ot. I see what u mean.

I was wondering about the input, tho. The text i use mentions input variations. Eg. " %d" means you need a space between every decimal integer you enter.
Similarly, " %s" means you should have a space between every text string.

Is this right? Other than that, I'm OK now. Thanks again!

4. The only thing you have to be concerned about here is the trailing input. scanf tends to leave stuff in the input stream, for example, the new line.

Do you want your input to be all on a single line? Like:

123.4 456.7 789.0 0.1

Or do you want it so they enter one, then hit enter, then enter another?

If the former, then you want something like:

scanf("%f %f %f %f %f", &var1, &var2, &var3, &var4, &var5 );

If the latter, you want something like:
scanf( "%f", &var );

In either case, you want to clear the rest of the input from the input stream. To do so, use the following:

while(fgetc(stdin)!='\n');

What this does is read one character from the input stream, and checks to see if it is the new line character. If so, it stops, if not, it reads the next.

What this will do is clear the input buffer after you call scanf. You can wrap this in a function and call a function to do it for you:
Code:
```void clearinput( void )
{
while(fgetc(stdin)!='\n');
}```
Then after you call scanf, call that function.

Quzah.

Popular pages Recent additions