Swapping %s for %c should solve the problem since you are trying to print
a single character and not a string, as already mentioned by the staff.
Just make sure to report a valid value from the ASCII table (remembering that
characters from 0 to 31 cannot be printed).
As improvement suggestions I would change void main to int main(), since you
is returning 0 at the end of the program (or else remove Return 0), remove the
system("clear") function calls if they are not necessary because they are
platform dependent (this code would not work in windows, for example,
that uses the cls command),use fgets to read the whole, so you wouldn’t need to
more of the fflush() function (but for that you would have to convert a string into
integer using atoi, for example), define a macro with the size
string maximum (making it easier to change its size later), put the
name and one variables inside the main function and remove the line break at the end
of the string returned by fgets, so the program does not skip a line after writing the name.
Follow the code with the suggested improvements:
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h> // para usar a função strlen()
#define TAMANHO_STR 20
int main()
{
char nome[TAMANHO_STR+1];
char num_str[TAMANHO_STR+1];
int num;
setlocale(LC_ALL, ("Portuguese"));
printf("\t\tLETRA DO ALFABETO\n ");
printf("\n\nOlá, digite aqui seu nome: ");
fgets(nome, TAMANHO_STR+1, stdin);
int l = strlen(nome); // descobre o comprimento da string
if (l > 0 && nome[l-1] == '\n') // se a string não é vazia e o último caractere é \n
nome[l-1] = 0; // define último caractere como \0
printf(" \n\nOlá %s, digite aqui o número para saber qua letra ele representa: ",nome);
fgets(num_str, TAMANHO_STR+1, stdin);
num = atoi(num_str);
printf("\n\n%s, o número %d representa a letra %c\n\n", nome, num, (char) num);
return 0;
}
Note that the last character of every string in C is 0, so set the length of the strings to TAMANHO_STR+1 and replace the penultimate character with 0.
Edit: As well remembered by a comment here, I forgot to explain that function fgets
saved in the string the line break character \n
, if it fits. That is, if you type as input abc
the string will receive abc\n\0
(if the string has 5 or more characters in this example). To remove this, the program finds the penultimate character and changes it to \0
, so the string can be printed without line break.
In the printf function use
%c
in place of%s
end to display the letter.– anonimo
I’ve tried, but nothing comes out, the place is empty.
– hiyan
In my test, using
%c
, worked perfectly. Make sure to provide fornum
a value corresponding to a printable character of the ASCII table (lower case letters: from 97 to 122.uppercase letters: from 41 to 90, other printable characters: see ASCII table).– anonimo
I think I managed to solve with your tip, really was putting wrong numbers to turn. Mt thank you!!!!
– hiyan