C - 从特定的单行输入填充数组

标签 c arrays input scanf

我是一名新手,对于我的学校编程练习,我需要从指定的输入创建整数数组。输入如下:

1000: { 250, 500, 750 }(输入)

我的非常基本的代码只能扫描以空格分隔的数字。

#include <stdio.h>
#include <stdlib.h>
#define LEN 10
long int array[LEN];

    int main()
    {   
        long int i;

        for (i =0; i < LEN; i++)
            {
            scanf("%li", &array[i]);
            }

    return 0;
    }

我有一个静态数组,我需要用 {} 括号中的数字填充它。 “:”符号之前的数字(在本例中为 1000)我可以作为单个变量或数组的第 0 个元素进行扫描。我可以使用一些修改过的 scanf 吗?但我认为这里的方法是使用 scanf 进行一些 while 循环。有时数组大于给定数字的数量,所以我需要用“}”符号结束循环。感谢您的想法。

最佳答案

考虑使用fgets来读取一行。使用 sscanf 解析该行。 %n 说明符将报告扫描处理的字符数。累积这些值将允许迭代该行。

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

#define SIZE 4000
#define LIMIT 500

int main( void) {
    char line[SIZE] = "";
    char bracket = 0;
    long int value[LIMIT] = { 0};
    int result = 0;
    int input = 0;
    int offset = 0;
    int span = 0;

    printf ( "enter values x:{w,y,...,z}\n");
    if ( fgets ( line, sizeof line, stdin)) {
        //scan for long int, optional whitespace, a colon,
        //optional whitespace, a left brace and a long int
        if ( 2 == ( result = sscanf ( line, "%ld : {%ld%n", &value[0], &value[1], &offset))) {
            input = 1;
            do {
                input++;
                if ( LIMIT <= input) {
                    break;
                }
                //scan for optional whitespace, a comma and a long int
                //the scan will fail when it gets to the right brace }
                result = sscanf ( line + offset, " ,%ld%n", &value[input], &span);
                offset += span;//accumulate processed characters
            } while ( 1 == result);
            //scan for optional space and character ie closing }
            sscanf ( line + offset, " %c", &bracket);
            if ( '}' != bracket) {
                input = 0;
                printf ( "line was not terminated with }\n");
            }
        }
    }
    else {
        fprintf ( stderr, "fgets EOF\n");
        return 0;
    }

    for ( int each = 0; each < input; ++each) {
        printf ( "value[%d] %ld\n", each, value[each]);
    }

    return 0;
}

关于C - 从特定的单行输入填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53459142/

相关文章:

c - libxml2如何处理碎片

c++ - `<cstdint>` 中使用的命名约定

javascript - 使用输入类型文件(多个)获取选择的文件并将它们存储在数组中

R 语言 - 等待用户输入 scan 或 readline

python - 蓝牙与 Python 和 Arduino (HC-06)

c - C中的运行时限制计时器

c - 搜索结构数组

javascript - 更新动态文本框中的现有值时在数组中创建新条目

php - 如何在 PHP 中向空数组添加元素?

python - 检查文件中是否有与输入匹配的文本