我試圖從用戶輸入中獲取一個帶有空格的字串,"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;
}
uj5u.com熱心網友回復:
你要這個:
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;
}
免責宣告:這是未經測驗的代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/374759.html
上一篇:根據Pandas資料框中的短語保留文本并洗掉所有其他文本
下一篇:嘗試..除了在執行緒內被忽略
