【问题标题】:Best Way to Convert Array of Strings to Array of Int in C在 C 中将字符串数组转换为 Int 数组的最佳方法
【发布时间】:2016-09-13 20:24:51
【问题描述】:

我当前的问题是从stdin 中读取未知数量的整数。我的方法是使用 gets() 将整行存储为 char 数组 (char str[50])。我正在尝试解析 char 数组并将每个“string int”转换为整数并存储在 int 数组中。我尝试使用 strtol (nums[i]=strtol(A, &endptr, 10) 其中A 是 char 数组。但是,当 A 的其余部分也是数字时,endptr 似乎不存储任何内容。例如,如果 A 是“8 hello” endptr=hello,但是当 A 为 "8 6 4" 时 endptr 什么都不是。

有没有更好的方法? atoi 可以做到这一点吗?任何帮助是极大的赞赏!谢谢!

char A[1000];
long nums[1000];
printf("Enter integers: ");
gets(A);
char *endptr;
int i=0;
while(endptr!=A){
    nums[i]=strtol(A, &endptr, 10);
    i++;
}

【问题讨论】:

  • 遍历数组并转换每个数字。有什么问题?显示您的代码。这不是编码服务。
  • 没有代码的模糊问题。可以发一些代码吗?
  • 如果 A="12 35 78" 我将如何遍历 char 数组?我可以将其转换为“1 2 3 5 7 8”,但这不是我需要的。
  • 我添加了一些我的原始代码。
  • 如果输入无效,1)停止。 2)跳过?例如输入:12 hello 34,获取 {12} 或 {12, 34}

标签: c atoi strtol


【解决方案1】:

这应该提取(正)整数并跳过其他不是整数的内容:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

char string[1024];
long numbers[512]; // worst case ~ 1/2 number of chars = "1 1 1 1 1 1 ... 1"

/* ... */

printf("Enter integers: ");
fgets(string, sizeof(string), stdin);

char *endptr, *ptr = string
int count = 0;

while (*ptr != '\0') {
    if (isdigit(*ptr)) {
        numbers[count++] = strtol(ptr, &endptr, 10);
    } else {
        endptr = ptr + 1;
    }

    ptr = endptr;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2011-04-13
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    相关资源
    最近更新 更多