Reputation: 4163
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;
}
Upvotes: 2
Views: 187
Reputation: 1621
you have declared the variable input with a static size 25 . So i don't see a chance of it getting a larger size for y = strlen(input);
Change your
char input[25];
to
char input[100];
anything more than 25.
Upvotes: 0
Reputation: 4869
nneonneo beat me to the answer:
The gets() function is equivalent to fgets() with an infinite size and a stream of stdin, except that the newline character (if any) is not stored in the string.
From http://www.manpagez.com/man/3/fgets/
I just added the references...
Upvotes: 0
Reputation: 5171
First of all, avoid gets()
in any serious code. gets()
is ill-designed and not safe. Never use it.
Second. fgets()
keeps the newline at the end of the buffer (while gets()
discards it).
Third, y <= 0
is probably wrong in the case of fgets()
, since it will likely read at least one character (the newline). You should replace it with y < 2
.
Last, and most important: please indent your code. :)
Upvotes: 1
Reputation: 179552
fgets
keeps the ending newline, whereas gets
throws it out.
Therefore, you'll have to change your check to y <= 1
if you use fgets
.
Upvotes: 6