c - 如何忽略或跳过数组中的某些字符并将数组的其余部分存储在 C 中?

标签 c arrays indexing token strtok

基本上,用户应该输入用逗号分隔的整数。然后应该将整数保存到另一个数组中。因此,假设用户输入:“1,20,31,42”,应该做的是将 1 保存在 array[0] 中,然后将 20 存储在 array[1] 中,等等。但不知何故,当我输入以下代码后,我下面的代码就会崩溃整数。我怎样才能解决这个问题?另外,如果用户输入“1,20,31,42”怎么办?如何忽略逗号和空格? strtok 中可以有多个分隔符吗?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void){
    // save input into a string
    char str[100];
    int coefficients[101], j;
    printf("enter number sep by commas: ");
    scanf("%99[^\n]", str);

    // get the first number (token)
    char* token;
    token = strtok(str, ",");
    int i;
    while (token != NULL){
        // convert the number into an integer (since its initially a char)
        i = atoi(token);

        // I want to store i in another array
        i = coefficients[j++];

        // get next number after the comma
        token = strtok(NULL, ",");
    }
    printf("%d", coefficients[0]);
} 

最佳答案

1. j 在您的程序中未初始化。

int coefficients[101], j;

在此处使用之前将其初始化为0 -

i = coefficients[j++];

2. 上面的表达式将把 coefficients 的值赋给 i (coefficients 也未初始化) 。像这样写-

coefficients[j++]=i;

3. 您使用 %c 说明符打印 int 变量,从而传递了调用 UB 的错误参数,此处 -

printf("%c", coefficients[0]);    
 /*     ^  use %d to print it */

Also, what if the user enters "1, 20, 31, 42"?

要使用空格输入,您可以像这样编写 scanf -

scanf("%99[^\n]", str);   // will read 99 characters until \n is encountered

Click here to see demo.

关于c - 如何忽略或跳过数组中的某些字符并将数组的其余部分存储在 C 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33149477/

相关文章:

字符指针和 printf

arrays - 为每个循环导入多个声音, ActionScript 3

ios - 使用嵌套快速枚举耗时过长,如何优化?

java - 用于实现 DBMS 的数组/列表 (Java)

c - 对学生数据库进行散列(使用链)(位折叠/加法散列)

mongodb - Mongo 中唯一的数组值

添加新索引值后,Postgresql 变得不负责任

python - C+Python 和核心转储

c++ - power() 的时间复杂度

c - 了解 pthread_detach