Read string pointer in C

Asked

Viewed 79 times

-1

This is the question: 4. Make a program that receives from the user the size of a string and call a function to dynamically allocate this string. Then the user must inform the contents of this string. The program prints the string without its vowels. The code usually works when the word does not have a space (' '), does not print the vowels, but when the word read has space, for example: 'good morning', prints everything nothing to see, symbols, something can help? Code below

char *ptr;
int i, x;
printf("Tamanho do vetor:\n");
scanf("%d", &x);
ptr = malloc(x * sizeof(char));
scanf("%s", ptr);
for (i=0; i<x; i++) {
if (*(ptr+i) != 'a' && *(ptr+i) != 'e' && *(ptr+i) != 'i' && *(ptr+i) != 'o' && *(ptr+i) != 'u') {
printf("%c", *(ptr+i));
}
}
  • With the format you specified in the scanf it will end the reading either when you reach the end of the line or when you find the first white. As you do not test whether you have reached the end of the string you will print memory junk. In your example your string will contain only "good".

  • then how could I?

1 answer

0

the most suitable way to work with string in c( compound words) would be to use scanf(" %[ n]s");. [ n] will read all your string to n, and the space you give between " and % is a way to clear the keyboard buffer. This may be your problem

  • thanks, I managed to fix

Browser other questions tagged

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