Reputation: 23
I'm on Win10, currently learning C, and I quite don't understand my output (EKEKEKEKE) for a simple exercice that ask for an input and give as output the same string without vowels.
inputBLABLABLA
EKEKEKE
outputB.L.B.L.B.L.
inputBLABLABLA
outputK.K.K.
int main()
{
for (int i = 0; i < 2; i = i + 1)
{
printf("input");
char titre[101] = {0};
scanf("%[^\n]\n", titre);
int j = 0;
char t = titre[0];
printf("output");
while ((t != '\0') && (j < 101))
{
if ((t != 'A')
&& (t != 'E')
&& (t != 'I')
&& (t != 'O')
&& (t != 'U')
&& (t != 'Y')
&& (t != ' '))
{
printf("%c.", t);
}
j = j + 1;
t = titre[j];
}
if (i == 0)
{
printf("\n");
}
}
}
Upvotes: 2
Views: 111
Reputation: 3650
Well, the problem is really with the scanf()
regular expression. Mainly that you're eating all characters except the newline, until you hit a newline. However, after matching all that scanf()
still doesn't return because it is still 'matching' more. By changing that expression so that am not matching a newline but an arbitrary character (which should be a newline), I'm able to get it to respond as you expect. I've also modified your code slightly to move some functionality to another function:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define INPUT_COUNT 2
#define BUFFER_SIZE 100
int is_vowel (char c)
{
const char *vowels = "AEIOUY ";
for (const char *s = vowels; *s != '\0'; s++) {
if (toupper(c) == *s) {
return 1;
}
}
return 0;
}
int main ()
{
for (int i = 0; i < INPUT_COUNT; i++) {
char c, titre[BUFFER_SIZE + 1] = {0};
// Scan in a line.
printf("Input:\t");
// %100 <- Limit 100 characters. %c <- Trick to get around newline issue
scanf(" %100[^\n]%c", titre, &c);
printf("Output:\t");
for (int j = 0; j < BUFFER_SIZE && titre[j] != '\0'; j++) {
if (!is_vowel(titre[j])) {
printf("%c.", titre[j]);
}
}
putchar('\n');
}
}
Upvotes: 1
Reputation: 669
You chould use gets to read a string like this :
int main()
{
for (int i = 0; i < 2; i = i + 1)
{
printf("input :");
char titre[101] = {0};
gets(titre);
int j = 0;
char t = titre[0];
printf("output :");
while ((t != '\0') && (j < 101))
{
if ((t != 'A')&&(t != 'E')&&(t != 'I')&&(t != 'O')&&(t != 'U')&&(t != 'Y')&&(t != ' '))
{
printf("%c.", t);
}
j = j + 1;
t = titre[j];
}
if (i == 0)
{
printf("\n");
}
}
}
Upvotes: 0