I'm a bit rusty on C. I'm in a school assignment that is asking me to make a program that gets user input, following that print the output. If the character count is higher than 50, to not print anything out and reprompt them. Quit should not print a count (in this case, 4).
This is what I have so far:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{ /*Start of main*/
printf("Type any word you'd like <= 50 characters.\nType quit to exit:\n");
char word[50];
int wordLength = 0;
while (strcmp(word, "quit") != 0)
{/*open of while loop (strcmp ... != 0)*/
scanf("%s\n", word);
wordLength = strlen(word);
if (wordLength > 50)
{
printf("Try again, >= 50 characters!:\n");
scanf("%s", word);
wordLength = strlen(word);
}
printf("%d\n", wordLength);
}/*End of while loop (strcmp... != 0)*/
return 0;
}/*End of main*/
I can't seem to get the length immediately following the submitted word. It appears to get wonky. It shows the number for the LAST submittted word after putting in a new word. It doesn't matter where I put the printf, it takes its time.
Can someone explain to me why it's so slow, and suggest a method I could implement to make it faster? This is a school assignment, please don't share direct answers, but guide me into the way I should be thinking? :)
I'm almost thinking this is inefficient coding with the delay.
You're all life savers!!!
Remove \n
from first scanf()
scanf("%s\n", word);
#---------^
Thanks to @remyable, \n
has different meaning in scanf()
- not the one you are expecting here to read newline. Refer C-faq 12.17
Also, checking for input for more than 50 chars that is not correct. You would get into buffer overrun. Look for different way to limit that.