C程序空格分开的整数输入字符串转换成int数组 [英] C program to convert input string of space separated ints into an int array

查看:454
本文介绍了C程序空格分开的整数输入字符串转换成int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:

我想打一个C程序,需要空格分隔整数的字符串作为输入(正面和负面的,可变的位数)和字符串转换为一个int数组。

I want to make a C program that takes a string of space separated ints as input (positive and negative, variable number of digits) and converts the string to an int array.

有是从字符串输入读取到整数Stack Overflow上的一个阵列的另一个问题,但它并不适用于数字长度超过1或负数的数字工作。

There is another question on reading ints from a string input into an array on Stack Overflow but it doesn't work for numbers of digit length more than 1 or negative numbers.

尝试:

#include <stdio.h>
int main () {
  int arr[1000], length = 0, c;
  while ((c = getchar()) != '\n') {
    if (c != ' ') {
      arr[length++] = c - '0';
    }
  }
  printf("[");
  for ( int i = 0; i < length-1; i++ ) {
    printf("%d,", arr[i]);
  }
  printf("%d]\n", arr[length-1]);
}

如果我输入以下到终端:

If I enter the following into terminal:

$ echo "21 7" | ./run
$ [2,1,7]

这是数组我得到:[2,1,7]而不是[21.7]

This is the array I get: [2,1,7] instead of [21,7]

如果我输入以下内容:

$ echo "-21 7" | ./run
$ [-3,2,1,7]

我得到:中[-3,2,1,7]而不是[-21,7]这是没有意义的。

I get: [-3,2,1,7] instead of [-21,7] which makes no sense.

不过,如果我输入:

$ echo "1 2 3 4 5 6 7" | ./run
$ [1,2,3,4,5,6,7]

请注意:我假设输入它总是空格隔开的整数的字符串

Note: I am assuming that the input it always a string of space separated integers.

推荐答案

完整的程序(改编自此答案由@onemasse )(不再需要输入无效停止读取输入):

Complete program (adapted from this answer by @onemasse) (no longer needs invalid input to stop reading input):

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

int main () {
    int arr[1000], length = 0, c, bytesread;
    char input[1000];
    fgets(input, sizeof(input), stdin);
    char* input1 = input;
    while (sscanf(input1, "%d%n", &c, &bytesread) > 0) {
        arr[length++] = c;
        input1 += bytesread;
    }
    printf("[");
    for ( int i = 0; i < length-1; i++ ) {
        printf("%d,", arr[i]);
    }
    printf("%d]\n", arr[length-1]);
    return 0;
}

scanf函数 / 的sscanf 手册页:

这些函数返回分配的输入项目的数量。这可以少于规定的,或者甚至是零,在匹配失败的情况下

These functions return the number of input items assigned. This can be fewer than provided for, or even zero, in the event of a matching failure.

因此​​,如果返回值是0,你知道,它无法再进行转换。

Therefore, if the return value is 0, you know that it wasn't able to convert anymore.

样I / O:

$ ./parse
1 2 3 10 11 12 -2 -3 -12 -124
[1,2,3,10,11,12,-2,-3,-12,-124]

注意:我目前无法确定究竟是如何工作的。我会考虑它。但是,如果有人理解,请编辑这篇文章,或发表评论。

NOTE: I am currently unsure of exactly how this works. I will look into it. However, if anyone understands, please edit this post or leave a comment.

这篇关于C程序空格分开的整数输入字符串转换成int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆