我试图从用户输入中获得一个带有空格的字符串,例如"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("%sn", 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("%sn", 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("%sn", stored[i]);
}
return 0;
}
免责声明:这是未经测试的代码。