Doubts about strings

Asked

Viewed 34 times

-2

I have a proposal to print on a theater ticket, date, time, part name (to be typed and read by scanf) and customer’s armchair number,

// declaração da variável.

char PecaTeatral[255];
// pulando para a leitura da string 

switch(n){      
case 1:

printf("\nNome da peca teatral\n");

scanf("%s", PecaTeatral);

printf("DATA : %s HORA: %s\nPeca : %s \t\t numero da poltrona: %d", __DATE__, __TIME__, PecaTeatral, ingresso_inicial); 

break;

// imprimi o ingresso do cliente, apos vendido

...

the difficulty in all this, how can I print a text, because the current code stores a word,

1 answer

1

You can use the scanf or the fgets, the most "famous" and that serve perfectly to read a sentence instead of a word.

  • Scanf: You’ll have to add the [^\n], to accept all characters except the enter button. You should also use as many characters as you want to read %51[^\n], will read a maximum of 51 characters in this example.

Ex: scanf("%254[^\n]s", PecaTeatral);

  • fgets: This example is easier and the most recommended, as it can read a sentence and limit characters without having to do great tricks.

Ex: fgets(PecaTeatral,254, STDIN);


It is possible to solve the problem with the function gets, however this function is extremely dangerous. If set as:

char PecaTeatral[10]; and the user writes more than 9 caracteres the program will give bug,

Browser other questions tagged

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