I am trying to get this code to verify that the user input a value. It works if i use gets() but when I change it to fgets() it stops working. I want it to keep looping until the user enters a string of at least 1 character but less than 25 I am new to programming if it isn’t apparent in my code. Thanks!
int main(void)
{
char input[25], inputNew[25];
int i;
int x;
int y;
do
{
printf("Please enter a string less then 25 characters!\n");
fgets(input, sizeof(input), stdin);
y = strlen(input);
}
while(y>25 || y<=0);
for (i = 0; i <= strlen(input); i++)
{
inputNew[i] = toupper(input[i]);
for (x = 1; x <= strlen(input); x+=2)
{
inputNew[x] = tolower(input[x]);
}
}
printf("The new value is: %s.\n", inputNew);
return 0;
}
fgetskeeps the ending newline, whereasgetsthrows it out.Therefore, you’ll have to change your check to
y <= 1if you usefgets.