Problem for centralized printing in C

Asked

Viewed 86 times

1

I have the following problem, in my code I want the program to centrally print the number 1 after the "word", and to center I am using the parameter "%-20s \t" to try to center the number after the word, but in words with more than one accent, it does not follow the tab.

Follow the source code:

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

int main(){
    setlocale(LC_ALL, "Portuguese");
    int i = 0;
    char nomes[3][15];
    strcpy(nomes[0], "palavra");
    strcpy(nomes[1], "palavrãozzz");
    strcpy(nomes[2], "palavrãozão");

    for(i = 0; i < 3 ; i++){
        printf("%-20s \t1\n", nomes[i]);
    }
}

The way out:

[Running] cd "c:\Users\Pierre\Desktop\1\" && gcc *.c -o main && "c:\Users\Pierre\Desktop\1\"main
palavra               1
palavrãozzz           1
palavrãozão           1


[Done] exited with code=0 in 0.242 seconds

I wish the way out was:

palavra                 1
palavrãozzz             1
palavrãozão             1

1 answer

1


The formatting of printf() was made to work with many simple texts, in ASCII. In fact all basic C functions are for well-standardized tasks, when you get out of the minimum need C programmers use third-party libraries or their own to do most of the tasks. A example can be seen in Soen.

The formatting of printf() does not work well with accents.

So the solution is to create something different to handle it well, or to make an algorithm that handles accented text, or at least to manually print character by character and not to use the formatting of printf(). Or still, what I think for an algorithm exercise that is what 99% of people do in C and no matter the details, do not use accent:

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

int main() {
    char nomes[3][15];
    strcpy(nomes[0], "palavra");
    strcpy(nomes[1], "palavraozzz");
    strcpy(nomes[2], "palavraozao");
    for (int i = 0; i < 3 ; i++) printf("%-20s\t1\n", nomes[i]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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