[英]Segmentation Fault for separating a string from user input than putting it to a array
我試圖從用戶輸入中獲取一個帶有空格的字符串,例如"abcd12314 asdfg92743 ppoqws21321"
並將它們分開,然后將它們存儲在一個數組中。 但它給了我一個分段錯誤
int main() {
char string[150];
int i = 0;
fgets(string, sizeof(string), stdin);
char *words = strtok(string, " ");
char *stored[150];
while (words != NULL) {
stored[i++] = words;
words = strtok(NULL, " ");
}
for (i = 0; i < strlen(string); i++) {
printf("%s\n", stored[i]);
}
return 0;
}
你要這個:
int main() {
char string[150];
int i = 0;
fgets(string,sizeof(string),stdin);
char *words = strtok (string, " ");
char *stored[150];
while (words != NULL) {
stored[i++] = words;
words = strtok (NULL, " ");
}
int nbofwords = i; // <<<< add this
for (i = 0; i < nbofwords; i++) { // change this line
printf("%s\n", stored[i]);
}
return 0;
}
但是這段代碼很容易出錯,你應該像下面這樣寫。 您應該在第一次使用時聲明變量並直接在for
語句中聲明循環計數器。
int main() {
char string[150];
fgets(string, sizeof(string), stdin);
char* stored[150];
int nbofwords = 0;
char* words = strtok(string, " ");
while (words != NULL) {
stored[nbofwords++] = words;
words = strtok(NULL, " ");
}
for (int i = 0; i < nbofwords; i++) {
printf("%s\n", stored[i]);
}
return 0;
}
免責聲明:這是未經測試的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.