Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int array doesnt get char values

Tags:

c

I am absolutely brand new at programming and im not sure how to explain what im doing here.

The whole purpose of this piece is to enter values and then print them out in the same order. Now I wanna quit from entering values when pressing 'q' and so I have to scanf for chars but when I assign them back to the int array the values are not the same.

Hope that makes any sense to you but in any case heres my code:

#include <stdio.h>
#include <stdlib.h>
#define SIZE  5000
define flush fflush(stdin)

main() {
    int input[SIZE] = {0},i = 0;
    int counter = 0;
    char inputs, quit;

     do {
        system("cls");
        printf("Input number ('q' to quit and display numbers entered): ");

        flush;
        scanf("%c",&inputs);
        flush;

        if (inputs == 'q')
            quit = 'q';
        else {
            input[i] = inputs;
            counter++;
            i++;
        }
    } while (i < SIZE && quit != 'q');

    for(i = 0; i < counter; i++){
        printf("%i.%i\n", i + 1, input[i]);
    }

    system("pause");
}

Ive been trying to do this on my own btw and also researched some information online regarding chars but couldnt find anything that would help me. Thanks a lot in advance.

like image 996
user1780004 Avatar asked Feb 23 '26 17:02

user1780004


1 Answers

You should nor be getting integer through %c neither assign char values to integers variables when that is not the intention, rather you should approach something like this

i = 0;
do {
  printf("Enter a number: ");
  scanf("%d", &input[i]);
  i++; counter++;
  printf("Do you want to continue? (y/n) : ");
  scanf("%c", &inputs);
} while(inputs == 'y');

or u can get the number of integer inputs upfront and loop to get that much integers.

like image 60
AnandVeeramani Avatar answered Feb 26 '26 05:02

AnandVeeramani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!