工作的地方我試圖讓程序運行,基本上需要輸入字符串,並通過一些代碼發送它,並按字母順序使用鏈接列表。我已經想出瞭如何使用手動(在實際代碼中)文本輸入來完成這項工作,但是當我嘗試從用戶那裏獲取輸入時,我無法使其工作。無法從用戶輸入代碼輸入代碼
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct llist {
char *value;
struct llist *next;
};
int compare (struct llist *one , struct llist *two)
{
return strcmp(one->value, two->value);
}
void add(struct llist **pp, char *value, int (*cmp)(struct llist *l, struct llist *r)) {
struct llist *new;
new = malloc(sizeof(*new));
new->value = value;
for (; *pp != NULL; pp = &(*pp)->next) {
if (cmp(*pp, new) > 0) break;
}
new->next = *pp;
*pp = new;
}
void display(struct llist *ptr) {
for (; ptr != NULL; ptr = ptr->next) {
printf("%s\n", ptr->value);
}
}
int main(void) {
struct llist *root = NULL;
char string;
printf("Please enter a string to be sorted alphabetically and displayed with a character count: ");
string = getchar();
while (string != 10){
add(&root,&string, compare);
string = getchar();
}
display(root);
return 0;
}
尋找在主函數中,我相當肯定它有事情做在使用getchar和事實,即它作爲整數讀取字符,但我無法弄清楚如何解決這個問題,輸出只是一堆空行。但是當while循環被刪除並且字符串像下面的main一樣輸入時,它工作正常嗎?爲什麼這樣呢?現在
int main(void) {
struct llist *root = NULL;
char string;
printf("Please enter a string to be sorted alphabetically and displayed with a character count: ");
add(&root,"t", compare);
add(&root,"h", compare);
add(&root,"i", compare);
add(&root,"s", compare);
add(&root,"m", compare);
add(&root,"y", compare);
add(&root,"t", compare);
add(&root,"e", compare);
add(&root,"x", compare);
add(&root,"t", compare);
display(root);
return 0;
}
輸出 Ë ^ h 我 米 小號 牛逼 牛逼 牛逼 X Ÿ
這是正確的, 誰能幫助我?
注意:爲什麼用'string!= 10'而不是'string!='\ n''? – chux
我原來使用的是,我不知道爲什麼我改變了它,但我把它切換回來,因爲它確實更有意義 – scarlso9
代碼是通過需要字符串的'strcmp()'進行「比較」。字段'value'是'&string'的副本,指向'char'的指針,但沒有''\ 0''終止符。 – chux