Reputation: 705
My little program below shall take 5 numbers from the user, store them into an array of integers and use a function to print them out. Sincerly it doesn't work and nothing is printed out. I can't find a mistake, so i would be glad about any advice. Thanks.
#include <stdio.h>
void printarray(int intarray[], int n)
{
int i;
for(i = 0; i < n; i ++)
{
printf("%d", intarray[i]);
}
}
int main ()
{
const int n = 5;
int temp = 0;
int i;
int intarray [n];
char check;
printf("Please type in your numbers!\n");
for(i = 0; i < n; i ++)
{
printf("");
scanf("%d", &temp);
intarray[i] = temp;
}
printf("Do you want to print them out? (yes/no): ");
scanf("%c", &check);
if (check == 'y')
printarray(intarray, n);
getchar();
getchar();
getchar();
getchar();
return 0;
}
Upvotes: 4
Views: 280
Reputation: 320381
Aside from the suggestions about printing the \n
character after your array (which are correct), you also have to be careful with your scanf
that expects the "yes/no" answer. Muggen was the first one to notice this (see his answer).
You used a %c
specified in your scanf
. %c
specifier in scanf
does not skip whitespace, which means that this scanf
will read whatever whitespace was left in the input buffer after you entered your array. You hit the "Enter" key after entering the array, which put a newline character into the input buffer. After that scanf("%c", &check)
will immediately read that pending newline character instead of waiting for you to enter "yes" or "no". That's another reason your code does not print anything.
In order to fix your scanf
, you have to force it to skip all whitespace characters before reading the actual answer. You can do that by scanf(" %c", &check)
. Note the extra space before %c
. Space character in scanf
format string forces it to skip all continuous whitespace beginning from the current reading position. Newline character happens to be whitespace, so it will be ignored by this scanf
.
Upvotes: 2
Reputation:
Change to that:
char check[2];
And also that:
scanf("%s", check);
if (!strcmp(check,"y"))
printarray(intarray, n);
Hope that helped. Your scanf("%c", &check);
failed. Instead of y
you end up having NL
(ASCII code 10
), which means the if
part fails.
I don't know if it a nice fix though. Maybe someone could give a better one. Keep in mind if you input something bigger (eg yess
) you going to get a bit unlucky ;)
Upvotes: 5
Reputation: 992837
Change your output in printarray()
to read:
printf("%d\n", intarray[i]);
^^
That will add a newline after each number.
Normally, output written to the console in C is buffered until a complete line is output. Your printarray()
function does not write any newlines, so the output is buffered until you do print one. However, you wait for input from the user before printing a newline.
Upvotes: 6