【问题标题】:Segmentation Fault for separating a string from user input than putting it to a array将字符串与用户输入分开而不是将其放入数组的分段错误
【发布时间】:2022-01-11 21:57:51
【问题描述】:

我试图从用户输入中获取一个带有空格的字符串,例如 "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;
}

【问题讨论】:

  • 你的for循环使用i &lt; strlen(string);,这是string中的字符数,而不是stored中的字符串数

标签: arrays c string segmentation-fault strtok


【解决方案1】:

你想要这个:

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;
}

免责声明:这是未经测试的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多