Doubt about a String issue (C Language)

Asked

Viewed 41 times

0

I wanted to ask a question about String, the activity asks me to print a sentence that was typed in alphabetical order, putting each word of the sentence in order. However, when I give Run in the program and type the sentence, depending on its size, not all words are put in order, it seems that there is a limitation error. I don’t know how to fix it, follow the code below:

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

int main()
{
char nm1[100], nm2[100], nm3[100], con;

        char alf[100] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','w','y','z','\0'};
        char alfb[100] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','W','Y','Z','\0'};
        
        printf("Digite uma frase: ");
        scanf("%s", &nm1);

        scanf("%s", &nm2);
        
        printf("Frase em ordem alfabetica: ");
        scanf("%s", &nm3);

        for(con = 0; con < 100; con++)
        {
            if(nm1[0] == alf[con]|| nm1[0] == alfb[con])
                printf(" %s", nm1);
            if(nm2[0] == alf[con]|| nm2[0] == alfb[con])
                printf(" %s", nm2);
            if(nm3[0] == alf[con]|| nm3[0] == alfb[con])
                printf(" %s", nm3);    
        }

    return 0;

}
  • Explain better what you want to do. If the sentence was typed alphabetically, what does it mean to "put the words of the sentence in order"? Note that the way you’re reading the phrase (scanf format %s) your phrase will not contain spaces as it delimits and closes the reading of the string.

1 answer

0

Your code has some errors:

The scanf() expects to receive a pointer to the variable to be read, as a vector alone is already a pointer &nm1 is not necessary, something like scanf("%s", nm1) would work better. But the argument "%s" reads a string to the space or line break (ENTER), and I believe your sentence has multiple spaces. To read the whole line I recommend the command fgets() which will read up to a line break(ENTER), Obs: it adds the value ' n' at the end of its string.

I also recommend that you check if one letter is larger than the other through the ASCII table.

A-Z letters are represented by numbers from 65 to 90 and from a-z 97 to 122.

To convert a char to ASCII int x = (int)'a'

Ascii table

Browser other questions tagged

You are not signed in. Login or sign up in order to post.