gpt4 book ai didi

将字符串转换为 int 数组

转载 作者:行者123 更新时间:2023-12-04 04:37:37 24 4
gpt4 key购买 nike

在用 C 编程时,我遇到了以下代码片段:

从字符数组转换时 input到整数数组 digit ,只有ANSI代码被转换为数字数组。

如何确保为该数组提供了正确的整数值?

这是相关代码:

int main(void) {
int x = 0;
int y = 0
char input[12] = {0};
int digit[12] = {0};

scanf("%s", &input[0]);
fflush(stdin);

while (input[y] != '\0') {
if (isdigit(input[y])) {
digit[x++] = input[y++];
count++;
}
else y++;
}
}

最佳答案

scanf("%s", &string[0]);  

读入 input字符数组。您正在阅读其他一些变量。
scanf("%s",input);

甚至最好
fgets(input,sizeof input, stdin );
  digit[x++] = input[y++]-'0';   
// substract `'0'` from your character and assign to digit array.

例如,如果 input[i]=='3' ==> '3'-'0'将产生整数 3

关于将字符串转换为 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19468556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com