简体   繁体   English

C程序将空间分隔的int的输入字符串转换为int数组

[英]C program to convert input string of space separated ints into an int array

Question: 题:

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. 我想创建一个C程序,它将一串空格分隔的int作为输入(正数和负数,可变数字位数)并将字符串转换为int数组。

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. 从Stack Overflow上的字符串输入读取整数还有另一个问题,但它不适用于数字长度大于1或负数的数字。

Attempt: 尝试:

#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]

This is the array I get: [2,1,7] instead of [21,7] 这是我得到的数组:[2,1,7]而不是[21,7]

If I enter the following: 如果我输入以下内容:

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

I get: [-3,2,1,7] instead of [-21,7] which makes no sense. 我得到:[ - 3,2,1,7]而不是[-21,7]这没有任何意义。

However, if I enter: 但是,如果我输入:

$ 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. 注意:我假设输入它总是一串空格分隔的整数。

This is a barebones version (no error checking, a trailing space should be left after the numbers), I am sure you can pick up from here: 这是一个准系统版本(没有错误检查,数字后应留下尾随空格),我相信你可以从这里拿起:

int main(void)
{
    int c;
    int i, num = 0, neg = 0;
    while ((c = getchar()) != EOF) {
        if (c != ' ') {
            if (c == '-') {
                neg = 1;
            } else {
                i = c - '0';
                num = num * 10 + i;
            }
        } else {
            (neg == 1) ? num *= -1 : num;
            printf("%d\n", num + 2);    // this is just to show that you indeed get an integer and addition works
            num = 0;
            neg = 0;
        }
    }
}

Complete program (adapted from this answer by @onemasse ) (no longer needs invalid input to stop reading input): 完整的程序(改编自@onemasse的答案 )(不再需要无效输入来停止读取输入):

#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;
}

From the scanf / sscanf man page: 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. 在匹配失败的情况下,这可能比提供的数量少,甚至为零。

Therefore, if the return value is 0, you know that it wasn't able to convert anymore. 因此,如果返回值为0,则表示无法再进行转换。

Sample I/O: 样本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. 但是,如果有人理解,请编辑此帖或发表评论。

I don't do much c, but here's my go :) 我做的不多,但这是我的去:)

#include"stdio.h"
#include"string.h"
#include"stdlib.h"

#define CHUNK 1000000

#define INT_COUNT 10000


int main(void) {
/*get all of the input*/
char temp_str[CHUNK] = "";
char* full_string = malloc(CHUNK * sizeof(char));
if (full_string == 0) {
    printf("Memory Error\n");
    exit(1);
}
int count = 2;
do {
    fgets(temp_str, CHUNK, stdin);
    strcat(full_string, temp_str);
    full_string = realloc(full_string, count * CHUNK * sizeof(char));
    if (full_string == 0) {
        printf("Memory Error\n");
        exit(1);
    }
    count++;
} while (strlen(temp_str) == CHUNK - 1 && temp_str[CHUNK - 2] != '\n');

//parse the input
char* token = strtok(full_string, " ");

int* arr = malloc(INT_COUNT * sizeof(int)), length = 0;
if (arr == 0) {
    printf("Memory Error\n");
    exit(1);
}

count = 1;

while (token != 0) {
    arr[length] = atoi(token);
    token = strtok(0, " ");
    length++;
    if (length == count * INT_COUNT) {
        count++;
        arr = realloc(arr, count * INT_COUNT);
        if(arr == 0) {
            printf("Memory Error\n");
            exit(1);
        }
    }
}

free(full_string);

//print the integers
for (int i = 0; i < length; i++) {
    printf("%d ", arr[i]);
    if (i % 20 == 0 && i != 0) {
        printf("\n");
    }
}

free(arr);

return 0;
}

Edited a little bit. 编辑了一下。 But there is minus problem, yet. 但是还有减号问题。 I ll look back later. 我稍后回顾一下。 If you tweak a little bit with this, I guess, it might work. 如果你稍微调整一下,我猜,它可能会奏效。 You try your way. 你尝试自己的方式。 I ll try mine. 我会试试我的。 But later. 但后来。

#include <stdio.h>
int main () {
  int arr[1000]={0}, length = 0, c, i;
  while (1) {
    c = getchar();

if(c=='-')
{
    //minus sign has problem yet. I ll come back once I have better soln.
}
else if(c==' ' || c=='\n')
{
    length-=2;
    arr[length]= arr[length]*10 + arr[length+1];
    length++;
    if(c=='\n')
    {
        break;
    }
}
else if (c != ' ') {
  arr[length++] = c - '0';
    }
 }
  printf("[");
  for (i = 0; i < length-1; i++ ) {
 printf("%d,", arr[i]);
  }
  printf("%d]\n", arr[length-1]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM