Alphabetizing a list in C, extra input -
this question has answer here:
- scanf issue when reading double 2 answers
sorry remedial question. been troubleshooting try , find error , have come empty.
i need write program alphabetizes list of inputs. first input integer value of number of inputs. each input ends new line character.
int main() { int word_total; char word_in[100][30], t[30]; int i, j; printf("\nplease number of words wish sort: \n"); scanf("%d", &word_total); printf("\nplease enter single word @ time. after each word, press return.\n"); (i = 0; < (word_total); i++) { scanf("%s\n", word_in[i]); } (i = 1; < (word_total); i++) { (j = 1; j < (word_total); j++) { if (strcmp(word_in[j - 1], word_in[j]) > 0) { strcpy(t, word_in[j - 1]); strcpy(word_in[j - 1], word_in[j]); strcpy(word_in[j], t); } } } printf("\nsorted list:\n"); (i = 0; < (word_total); i++) { printf("%s\n", word_in[i]); } printf("\n"); } the problem: input of words takes word_total + 1. instance, if word_total = 5, have input 6 words. last word input ignored , not included in "sorted list". can fix problem by:
for (i = 0; < (word_total - 1); i++) { scanf("%s\n", word_in[i]); } but "sorted list" short 1 word. i've tried changing "<" "<=", etc, haven't found fix.
thank help!
the problem seems be
scanf("%s\n", word_in[i]); which, due "\n", attempt read more whitespace following string (until finds non-whitespace; note any whitespace character means any number of whitespace characters; \n not match single newline apparently expect). should remove "\n" scanf format , eat newline getchar() or similar.
ps: not testing return value scanf() asking trouble.
Comments
Post a Comment