如何忽略或跳过数组中的某些字符并将数组的其余部分存储在 C 中?
How do you ignore or skip certain characters in an array and store the rest of the array in C?
基本上,用户应该输入以逗号分隔的整数。然后应将整数保存到另一个数组中。所以假设用户输入:“1,20,31,42”应该做的是将 1 保存在数组 [0] 中,然后将 20 保存在数组 [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[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"?
要使用 space 进行输入,您可以这样写 scanf
-
scanf("%99[^\n]", str); // will read 99 characters until \n is encountered
基本上,用户应该输入以逗号分隔的整数。然后应将整数保存到另一个数组中。所以假设用户输入:“1,20,31,42”应该做的是将 1 保存在数组 [0] 中,然后将 20 保存在数组 [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[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"?
要使用 space 进行输入,您可以这样写 scanf
-
scanf("%99[^\n]", str); // will read 99 characters until \n is encountered