Problem with Printf and Scanf

0

I want to make my program ask to enter a sentence and then a letter but even though the phrase asks for it the letter does not ask for it yet IF it shows the text "Letter:" that follows that the command line of the console starts ...

The code is this:

char frase[100];
char letra;


printf("Frase: ");

scanf("%s", frase);

printf("Letra: ");

scanf("%c", &letra);

Also, I think that if my sentence contains more than one word then I do not consider it ...

thanks!

    
asked by Edu 06.03.2018 в 22:47
source

1 answer

1

With

scanf("%s", frase);

In frase all the characters that are written will be stored until:

  • Read all the buffer
  • Found a line break
  • A blank space is found

By this last condition, '% s' is not able to read complete lines. For this purpose you have getline :

int n;
char frase[100];

getline(frase,&n,stdin);

Although you can also try to program it on your own:

char* ptr = frase;
int c;
while( (c = getchar()) != EOF )
{
  if( *ptr == '\n' )
  {
    *ptr = '
for( int i=0; i<99; i++ )
{
  int c = getchar();
  if( c == EOF || c == '\n' )
  {
    frase[i] = '
scanf("%s", frase);
'; break; } frase[i] = (char)c; } frase[99] = '
int n;
char frase[100];

getline(frase,&n,stdin);
'; printf("\n%s",frase);
'; break; } *ptr = (char)c; ++ptr; } printf("\n%s",frase);

Or, checking that you do not exceed 100 characters:

char* ptr = frase;
int c;
while( (c = getchar()) != EOF )
{
  if( *ptr == '\n' )
  {
    *ptr = '
for( int i=0; i<99; i++ )
{
  int c = getchar();
  if( c == EOF || c == '\n' )
  {
    frase[i] = '%pre%';
    break;
  }
  frase[i] = (char)c;
}

frase[99] = '%pre%';

printf("\n%s",frase);
'; break; } *ptr = (char)c; ++ptr; } printf("\n%s",frase);
    
answered by 06.03.2018 / 22:58
source