简体   繁体   English

用C中的scanf填充Char数组

[英]filling a Char array with scanf in C

How can I fill an empty Char Array with keyboard? 如何用键盘填充空的字符数组? something like 就像是

char a_string[];
while("if not Q")
{
printf("Enter a number: ");
scanf("%c", a_string);
}

I know this is wrong I just want to know how to give values to my a_string[], without limiting the size. 我知道这是错误的,我只想知道如何在不限制大小的情况下为a_string []赋值。 so the size will vary depend on how many keys i'm gonna enter from keyboard. 因此大小会有所不同,具体取决于我要从键盘输入多少键。

Thanks! 谢谢!

Try this: 尝试这个:

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

int main() {
    char *string = NULL;
    char *newstring = NULL;
    char c = '\0';
    unsigned int count = 0;

    while(c != 'Q'){
        c = getc(stdin);
        if(string == NULL){
            string = (char *) malloc(sizeof(char)); // remember to include stdlib.h
            string[0] = c;
        }
        else{
            newstring = (char *) realloc(string, sizeof(char)*count);
            string = newstring;
            string[count] = c;
        }
        count++;
    }

    string[count-1] = '\0';  // remove the Q character
    fprintf(stderr,"here you are: %s",string);
    free(string); // remember this!
    return 0;
}

If you will know at the start of runtime how many keys you'll enter, you can have it ask first for the number of keys and then for the individual characters, as in the untested snippet below. 如果您在运行时开始时知道要输入多少个键,则可以让它首先询问键的数量,然后询问各个字符,如下面未经测试的代码段所示。

Otherwise, you have to set some real-world maximum (eg 10000) that will never be reached, or, if that's not possible, set a per-array maximum and make provisions for rollover into a new array. 否则,您必须设置一些实际无法达到的最大值(例如10000),或者,如果不可能,则为每个阵列设置最大值,并为过渡到新阵列做好准备。 That last option really is the same (eventually bounded by memory) but gives you a larger maximum. 最后一个选项实际上是相同的(最终受内存限制),但为您提供了更大的最大值。

char *mychars;
int numchars;

printf("Please enter the total number of characters:\n");
if (scanf("%d", &numchars) == NULL) {
  printf("couldn't read the input; exiting\n");
  exit(EXIT_FAILURE);
}

if (numchars <= 0) {
  printf("this input must be positive; exiting\n");
  exit(EXIT_FAILURE);
}

mychars = (char *) malloc (numchars * sizeof(char));

int current_pos = 0;
printf("Enter a digit and hit return:\n");

while (scanf("%c", &mychars[current_pos]) != NULL && current_pos < numchars) {
  current_pos++;
  printf("Enter a digit and hit return:\n");
}

Repetitive calls to realloc() will meet the need. 重复调用realloc()将满足需要。

Double realloc() size as needed to avoid O(n) calls. 根据需要加倍realloc()大小,以避免O(n)调用。

char *GetQLessString(void) {
  size_t size_alloc = 1;
  size_t size_used = size_alloc;
  char *a_string = malloc(size_alloc);
  if (a_string == NULL) {
    return NULL; // Out  of memory
    }

  char ch;
  while(scanf("%c", &ch) == 1 && (ch != 'Q')) {
    size_used++;
    if (size_used > size_alloc) {
      if (size_alloc > SIZE_MAX/2) {
        free(a_string);
        return NULL; // Too big - been typing a long time
      }
      size_alloc *= 2; 
      char *new_str = realloc(a_string, size_alloc);
      if (new_str == NULL) {
        free(a_string);
        return NULL; // Out  of memory
      }
      a_string = new_str;
    }
    a_string[size_used - 2] = ch;
  }

  a_string[size_used - 1] = '\0';
  return a_string;
}

Code could do a final realloc(a_string, size_used) to trim excess memory allocation. 代码可以执行最后的realloc(a_string, size_used)来减少多余的内存分配。
Calling routine needs to call free() when done with the buffer. 完成缓冲区后,调用例程需要调用free()
The following would be cleaner. 以下将更清洁。

int ch;
while((ch = fgetc(stdin)) != EOF && (ch != 'Q')) {

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

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