I want to check is the user inputs a word that has more than 10 characters.If he does,let's say we exit the program.
This not my code,so do not comment the global variables etc...
Code:
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
typedef struct {
wchar_t term[10];
int freq;
} word_t;
/* global array of words */
word_t words[5000];
int n_words = 0;
int find_word(wchar_t s[]) {
int i;
for (i=0; i < n_words; i++)
if (wcsncmp(s, words[i].term,10) == 0)
return i;
return -1;
}
void add_word(wchar_t s[]) {
assert(wcslen(s) <= 10);
wcsncpy(words[n_words].term, s,10);
words[n_words].freq = 1;
n_words++;
}
int main(void) {
char myStr[11];
wchar_t s[11];
setlocale(LC_CTYPE,"UTF-8");
printf("Please type a word with 10 characters at most\n");
/*could use fgetws and wprintf instead*/
while ((fgets(myStr,10,stdin)!= NULL)) {
if(strlen(myStr)>10)
{
printf("Word with more than 10 characters detected, so exiting...\n");
return -1;
}
mbstowcs(s,myStr,strlen(myStr));
int i = find_word(s);
if (i == -1)
{
add_word(s);
printf("1: %s\n", myStr);
}
else
{
words[i].freq++;
printf("%d: %s\n",words[i].freq ,myStr);
}
printf("Please type a word with 10 characters at most\n");
}
return 0;
}
When the user enters a word larger than 10 characters,then this word will split at the 10-nth character because of the fgets (with scanf and %10 it will be the same i guess),so it will re-loop without getting anything anything from input ,reading the rest of the word (if it is less than 20 characters).
I thought to go dynamically and ask the user for the size of the buffer but then again i have to make sure that the user will not overflow my little buffer.
Also an idea of declaring a larger array before, breaks my heart because it is such a waste of memory.
So maybe i could look at the end of the loop and determine if there is some letters left in the stdin buffer.If so this means that the user typed a bigger word than 10 characters.
Any ideas?