Thread: C program not outputting correctly

  1. #1
    Registered User
    Join Date
    Sep 2017
    Posts
    2

    C program not outputting correctly

    Hello, I have this program that asks the user to enter 10 characters. I store these characters in an array and sort them using a bubble sort. However, when I run it, it reads in the Enter key and the character both, but the Enter key is not suppose to be a character. How can I fix this? I am trying to learn C but I am struggling. If anyone is willing to help me I will greatly appreciate it


    Code:
    #include <stdio.h>
    #include <stdbool.h>
    
    
    void bubbleSort(char *);
    int main(){
        char *arr=(char *)malloc(11*sizeof(char));
        int i;
        char input;
    
    
    
    
        for( i=0;i<10;i++, input = '\0'){
    
    
            printf("Enter character number %d:\n", i+1);
    
    
            scanf("%c", (arr+i));
    
    
    
    
        }
    
    
    
    
    
    
        bubbleSort(arr);
    
    
        printf("The sorted characters are:\n");
        for(i=0;i<10;i++){
    
    
            printf("%c ", *(arr+i));
        }
    
    
        printf("\n");
    }
    
    
    void bubbleSort(char *arr){
        char temp;
        bool swap;
    
    
        do{
            swap = false;
            int i;
            for( i = 0; i < 10; i++ )
            {
                if(*(arr + i)< *(arr + i + 1)){
                    temp = *(arr + i);
                    *(arr + i) = *(arr+ i +1 );
                    *(arr+ i + 1) = temp;
                    swap = true;
    
    
                }
            }
    
    
        }while(swap);
    
    
    
    
    }

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    scanf can be told to ignore whitespace( newline, tab, space, etc ). Just add a single space before the %c inside the string.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Sep 2017
    Posts
    2
    Oh thank you so much. I didn't know that, you're awesome

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Program not outputting to console
    By jjwooyoung in forum C Programming
    Replies: 8
    Last Post: 10-11-2015, 11:53 AM
  2. Replies: 2
    Last Post: 09-09-2014, 02:36 PM
  3. Flight program not outputting
    By bigmac(rexdale) in forum C++ Programming
    Replies: 1
    Last Post: 06-15-2008, 05:32 PM
  4. can't get this program to run correctly
    By Amyaayaa in forum C++ Programming
    Replies: 3
    Last Post: 02-05-2008, 04:16 PM
  5. Weird, cards not outputting correctly
    By Shamino in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2007, 03:26 PM

Tags for this Thread