Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当我不知道在C中会分配多少值时,如何使用scanf?_C_Arrays_Scanf - Fatal编程技术网

当我不知道在C中会分配多少值时,如何使用scanf?

当我不知道在C中会分配多少值时,如何使用scanf?,c,arrays,scanf,C,Arrays,Scanf,以下是说明: “从标准输入读取字符,直到读取EOF(文件结尾标记)。不要提示用户输入文本-只要程序启动就读取数据。” 因此,用户将输入字符,但我不知道有多少。稍后我将需要使用它们来构建一个表,该表显示输入的每个值的ASCII代码 我该怎么做 这是我的主意 int main(void){ int inputlist[], i = -1; do {++i;scanf("%f",&inputlist[i]);} while(inputlist[i] !=

以下是说明: “从标准输入读取字符,直到读取EOF(文件结尾标记)。不要提示用户输入文本-只要程序启动就读取数据。”

因此,用户将输入字符,但我不知道有多少。稍后我将需要使用它们来构建一个表,该表显示输入的每个值的ASCII代码

我该怎么做

这是我的主意

int main(void){
     int inputlist[], i = -1;
     do {++i;scanf("%f",&inputlist[i]);}
         while(inputlist[i] != EOF)

你说的是角色,所以这可能是

char arr[10000];
ch=getchar();
while(ch!=EOF)
{
   arr[i++]=ch;
   ch=getchar();
}
//arr[i]=0; TO make it a string,if necessary.
和转换为ASCII

for(j=0;j<i;j++)
     printf("%d\n",arr[j]);
PPS:仅当您的输入为每行一个字符时,此选项才有效


scanf
EOF
上返回
EOF
,您在开始解决方案时进行了合理的尝试,但出现了一些错误。如果不指定大小,就无法定义数组,因此
intinputlist[]
甚至不应该编译。您的
scanf()
说明符是float的
%f
,这两次是错误的(一次是因为您用整数类型声明了
inputlist
,两次是因为您说您的输入是字符,所以您应该告诉
scanf()
使用
%c
%s
),实际上,如果在
EOF
之前一直在无条件地读取输入,则应该使用无条件输入函数,例如
fgets()
fread()
。(或
read()
,如果您愿意的话)

您需要两样东西:一个用来存储当前输入块的地方,以及一个用来存储您已经读入的输入的地方。因为我上面提到的输入函数期望您指定输入缓冲区,所以您可以通过一个简单的声明来分配它

char input[1024];
但是,对于存储所有输入的位置,您需要动态分配一些内容。最简单的解决方案是简单地
malloc()
一块存储,跟踪它的大小,并在必要时
realloc()

char *all_input;
int poolsize=16384;
all_input = malloc(pool_size);

然后,只需在输入函数上循环,直到返回值表明已达到EOF,然后在循环的每次迭代中,将输入数据附加到存储区域的末尾,根据输入数据的大小增加一个计数器,并检查是否过于接近输入存储区域的大小。(如果是,则使用
realloc()
扩展存储。)

您可以通过getchar读取输入,直到达到EOF。如果不知道输入的大小,应该在堆中使用动态大小缓冲区

char *buf = NULL;
long size  = 1024;
long count = 0;
char r;

buf = (char *)malloc(size);
if (buf == NULL) {
    fprintf(stderr, "malloc failed\n");
    exit(1);
}   

while( (r = getchar()) != EOF) {
    buf[count++] = r;
    // leave one space for '\0' to terminate the string 
    if (count == size - 1) {
        buf = realloc(buf,size*2);
        if (buf == NULL) {
            fprintf(stderr, "realloc failed\n");
            exit(1);
        }   
        size = size * 2;
    }   
}   
buf[count] = '\0';
printf("%s \n", buf);

return 0;

以下是满足您需求的完整解决方案,并附有评论。

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

// Number of elements
#define CHARNUM 3

int main(int argc, char **argv) {
    // Allocate memory for storing input data
    // We calculate requested amount of bytes by the formula:
    // NumElement * SizeOfOneElement
    size_t size = CHARNUM * sizeof(int);

    // Call function to allocate memory
    int *buffer = (int *) calloc(1, size);

    // Check that calloc() returned valid pointer
    // It can: 1. Return pointer in success or NULL in faulire
    //         2. Return pointer or NULL if size is 0 
    //            (implementation dependened). 
    //            We can't use this pointer later.

    if (!buffer || !size)
    {
        exit(EXIT_FAILURE);
    }

    int curr_char;
    int count = 0;
    while ((curr_char = getchar()) != EOF)
    {
        if (count >= size/sizeof(int))
        {
            // If we put more characters than now our buffer
            // can hold, we allocate more memory
            fprintf(stderr, "Reallocate memory buffer\n");
            size_t tmp_size = size + (CHARNUM * sizeof(int));
            int *tmp_buffer = (int *) realloc(buffer, tmp_size);
            if (!tmp_buffer)
            {
                fprintf(stderr, "Can't allocate enough memory\n");
                exit(EXIT_FAILURE);
            }
            size = tmp_size;
            buffer = tmp_buffer;
        }
        buffer[count] = curr_char;
        ++count;
    }


    // Here you get buffer with the characters from 
    // the standard input
    fprintf(stderr, "\nNow buffer contains characters:\n");
    for (int k = 0; k < count; ++k)
    {
        fprintf(stderr, "%c", buffer[k]);
    }
    fprintf(stderr, "\n");

    // Todo something with the data

    // Free all resources before exist
    free(buffer);
    exit(EXIT_SUCCESS); }

请注意,如果您使用的是
getline()
,那么无论如何都应该使用动态分配内存。但不是为了存储字符,而是为了存储指向字符串的指针。

有几个错误。您正在尝试将浮点读入整数变量。此外,您正在写入inputlist数组,而没有为其分配内存。最好更改标题,因为问题不在scanf()中。问题在于内存管理。在C中,不要强制转换
malloc()
函数返回的值。非常感谢!我感到困惑的一点是,用户如何输入EOF值来阻止getchar()函数请求输入?@user3321551“Ctrl”+“D”代表linux中的EOF。在开始时为什么将CHARNUM声明为3中,您可以更详细地参考哪个?如果(count>=size/sizeof(CHARNUM))应该表示什么?它应该是
size/sizeof(int)
-内存中的字符数。我修好了。
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

// Number of elements
#define CHARNUM 3

int main(int argc, char **argv) {
    // Allocate memory for storing input data
    // We calculate requested amount of bytes by the formula:
    // NumElement * SizeOfOneElement
    size_t size = CHARNUM * sizeof(int);

    // Call function to allocate memory
    int *buffer = (int *) calloc(1, size);

    // Check that calloc() returned valid pointer
    // It can: 1. Return pointer in success or NULL in faulire
    //         2. Return pointer or NULL if size is 0 
    //            (implementation dependened). 
    //            We can't use this pointer later.

    if (!buffer || !size)
    {
        exit(EXIT_FAILURE);
    }

    int curr_char;
    int count = 0;
    while ((curr_char = getchar()) != EOF)
    {
        if (count >= size/sizeof(int))
        {
            // If we put more characters than now our buffer
            // can hold, we allocate more memory
            fprintf(stderr, "Reallocate memory buffer\n");
            size_t tmp_size = size + (CHARNUM * sizeof(int));
            int *tmp_buffer = (int *) realloc(buffer, tmp_size);
            if (!tmp_buffer)
            {
                fprintf(stderr, "Can't allocate enough memory\n");
                exit(EXIT_FAILURE);
            }
            size = tmp_size;
            buffer = tmp_buffer;
        }
        buffer[count] = curr_char;
        ++count;
    }


    // Here you get buffer with the characters from 
    // the standard input
    fprintf(stderr, "\nNow buffer contains characters:\n");
    for (int k = 0; k < count; ++k)
    {
        fprintf(stderr, "%c", buffer[k]);
    }
    fprintf(stderr, "\n");

    // Todo something with the data

    // Free all resources before exist
    free(buffer);
    exit(EXIT_SUCCESS); }
errno = 0; 
int read = 0; 
char *buffer = NULL;
size_t len = 0;
while ((read = getline(&buffer, &len, stdin)) != -1) 
{ // Process line } 

if (errno) { // Get error }

// Process later