Home > Software design >  How to sort and show an input (using scanf) stored by char array?
How to sort and show an input (using scanf) stored by char array?

Time:10-07

I’ve got a problem in sorting a char array like “ANF23ie89Z” and get an output like “2389AFNZei” (by ascii code), what I’ve tried


#include <iostream>
#include <stdio.h>

using namespace std;

int main(){
    char arr[20];
    
    for(int i = 0; i < 20; i  ){
        scanf(“%s”, &arr[i]);
        getchar();
    }
    
    for(int i = 0; i < 20; i  ){
        for(int j = 0; j < 20 - i - 1; j  ){
            if(arr[j] > arr[j 1]){
                int tmp = arr[j 1];
                arr[j 1] = arr[j];
                arr[j] = tmp;
            }
        }
    }
 
    for(int i = 0; i < 20; i  ){
        printf(“%s”, arr[i]);
    }
    puts(“”);
    return 0;
}

My idea is storing “ANF23ie89Z” to array like arr[0] = ‘A’, arr[1] = ‘N’,… and sort them by bubble sort & ascii, and last print my input.

But I got nothing in output.

(I know I can use algorithm sort. to sort but my main problem is not about sorting, it’s about scanf(%s) & printf(%s) ?)

Please help!

CodePudding user response:

I am not quiet sure why you're looping over scanf or over printf.This would work without sorting and now you just need a working sorting algorithm

int main(){
    char arr[20];
    scanf("%s", arr);
    
    printf("%s", arr);
    return 0;
}

CodePudding user response:

The characteristics of your code fit more closely to a C program, so analyzing what you are trying to accomplish, following is a version of your code with the usual usage of "scanf" and "printf".

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    char arr[20];

    printf("Enter an array of characters: ");
    scanf("%s", arr);                           /* Input your text into an array, not character by character */

    for(int i = 0; i < (strlen(arr) - 1); i  ){
        for(int j = 0; j < (strlen(arr) - i) - 1; j  ){
            if(arr[j] > arr[j 1]){
                int tmp = arr[j 1];
                arr[j 1] = arr[j];
                arr[j] = tmp;
            }
        }
    }

    for(int i = 0; i < strlen(arr); i  ){
        printf("%c", arr[i]);               /* Use %c for printing a character */
    }
    printf("\n");

    return 0;
}

First off, it is usual and customary to input text with the "%s" format along with the array name (not an individual character position). Also, so as to not go out of bounds, it is usual to utilize the "strlen" function to ensure that the program does not read past the end of the string being analyzed.

With those bits, following is the output I got from entering your test string.

@Una:~/C_Programs/Console/SortWord/bin/Release$ ./SortWord 
Enter an array of characters: ANF23ie89Z
2389AFNZei

Give that a try to see if it meets the spirit of your project.

CodePudding user response:

You can just use scanf("%s", var-name); to store the string data. `

#include <stdio.h>

int main(){
 char arr[20];
 scanf("%s", arr);

 for(int i = 0; i < 20; i  ){
    for(int j = 0; j < 20 - i - 1; j  ){
        if(arr[j] > arr[j 1]){
            int tmp = arr[j 1];
            arr[j 1] = arr[j];
            arr[j] = tmp;
        }
    }
 }

 for(int i = 0; i < 20; i  ){
    printf("%c", arr[i]);
 }
 return 0;
}
//////////////////////////////////////

`

The input was “ANF23ie89Z” and the output was “2389AFNZei”.

CodePudding user response:

printf with %s goes through all the characters of the string (pointer to char) you gave as argument until it finds a null char. Thats because strings in C are ended with a null char to denote where the string ends. You gave it char not char * thats why it doesnt work as you want. To print a single character, use printf with %c instead.

CodePudding user response:

My idea is storing “ANF23ie89Z” to array like arr[0] = ‘A’, arr[1] = ‘N’,… and sort them by bubble sort & ascii, and last print my input.

If you want to read one character at a time, each on a separate line, with scanf, then you should use the %c scanf directive (together with some means of consuming the newlines, which your getchar() call provides), and loop once per character you want to read. Example:

    char arr[20];
    puts("Input 20 characters, one per line:");
    for(int i = 0; i < 20; i  ){
        scanf("%c", &arr[i]);
        getchar();
    }

Do note that that is at risk to fall out of register if the user types any trailing characters on a line or any blank lines.

If you want to read all the characters on one line, and are prepared to assume that none are space or tab (or other whitespace) characters, then one scanf() call with a %s directive will accomplish it. Example:

    char arr[21];  // <-- one byte is reserved for a string terminator

    puts("Input 20 characters on one line, with no spaces or tabs:");
    scanf(" s", arr);           // <-- field width prevents buffer overrun
    int num_chars = strlen(arr);  // <-- sort only this many characters

You have instead used a mishmash of the two. It might serendipitously work about as you expect for the one character per line case, but at minimum, it will overrun the bounds of your array by at least one byte in that case because you do not leave room for a string terminator after the 20th character.


But I got nothing in output.

That would be for a different, but related reason: your arr[i] is one character, not a string. When you tell printf to interpret it as a string via the %s directive, you elicit undefined behavior, which is extremely unlikely to be printing the value as if it were a character. I'm surprised that the program does not fail with your system's flavor of memory-access fault. Or does it? That would have been relevant information to include in the question.

In any case, the situation on output is analogous to the one on input: either print characters, one at a time, with %c, or print a whole string, all at once, with %s (or other, similar variations). In the latter case, you must actually have a string, meaning that the data are terminated by a null character. Examples:

    // one character at a time, each on its own line
    for(int i = 0; i < 20; i  ){
        printf("%c\n", arr[i]);
    }

    /* OR */

    // all characters on the same line, assuming arr contains a string
    printf("%s\n", arr);

Note also: if you decide to go the string route, be sure to exclude the terminator from your sort. It needs to stay at the end of the string, else the effect will be a logical truncation of the string -- probably to an empty string.

  • Related