Functions and Arrays

My little program below should take 5 numbers from the user, save them into an array of integers and use the function to print them. Sincerely this does not work, and nothing is printed. I cannot find a mistake, so I would be happy for 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; } 
+4
source share
4 answers

Change to this:

 char check[2]; 

And also that:

 scanf("%s", check); if (!strcmp(check,"y")) printarray(intarray, n); 

Hope this helps. Your scanf("%c", &check); failed. Instead of y you get NL (ASCII code 10 ), which means that the if part fails.

I do not know if this is good. Maybe someone can give the best. Keep in mind if you yess something more (e.g. yess ) you will be a little out of luck ;)

+5
source

Change your output in printarray() as follows:

  printf("%d\n", intarray[i]); ^^ 

This will add a new line after each number.

Typically, the output written to the console in C is buffered until a complete line is output. Your printarray() function does not write newlines, so the output is buffered until you print it. However, you are waiting for input from the user before printing a new line.

+6
source

Aside from suggestions for printing the \n character after your array (which is correct), you should also be careful with your scanf , which is expecting a yes / no response. Muggen was the first to notice this (see His answer).

You used %c specified in scanf . The %c scanf in scanf does not skip spaces, which means that this scanf will read all the spaces left in the input buffer after entering your array. You get to the "Enter" key after entering an array that places a newline character in the input buffer. After that, scanf("%c", &check) will immediately read this pending newline character instead of waiting for the input to be yes or no. This is another reason your code doesn't print anything.

To fix your scanf , you must force it to skip all whitespace before reading the actual answer. You can do this with scanf(" %c", &check) . Note the extra space in front of %c . The space character in the scanf format string makes it skip all contiguous spaces, starting at the current reading position. The newline is white, so this scanf will be ignored.

+2
source
 printf("%d", intarray[i]); 

add new line after that

0
source

Source: https://habr.com/ru/post/1335798/


All Articles