简体   繁体   English

从C中的输入动态读取字符串

[英]Dynamically read string from input in C

I'm trying to read in a value user input and store it in a string. 我试图读取值用户输入并将其存储在字符串中。 The string must be all the characters before a comma or the end of the line, and it needs to output either the comma, or the EOF. 该字符串必须是逗号或行尾之前的所有字符,并且需要输出逗号或EOF。

I'm trying to read each character in and allocate space in the string as needed but the file stops after reading the first input. 我试图读取每个字符并根据需要在字符串中分配空间,但是文件在读取第一个输入后停止。

This is what I have so far: 这是我到目前为止的内容:

char read_data(char** str) {
  char c = 'n';
  int size = sizeof(**str);

  int i = 0;
  while (((c = getchar()) != COMMA) && (c != NEWLINE)) {
    size += sizeof(c);

    *str = (char*) realloc(*str, size + 1);
    assert(*str);

    *str[i] = c;
    i++;

  }

  *str[i] = '\0'; //terminator
  return c;
}

int main(int argc, char const *argv[]) {
  char* string = NULL;
  char left;
  left = read_data(&string);
  printf("left: %c\n", left);
  printf("string: %s\n", string);

  free(string);
  return 0;
}

I can't work out why it's breaking. 我无法弄清楚它为什么破裂。 Would anyone have any tips/ideas..? 任何人都有任何技巧/想法吗?

Because array subscripting ( [] ) has higher precedence than indirection ( * ) , when you write *str[i] you get *(str[i]) -- the first character of the i th string. 因为数组下标( [] )比间接寻址( * )具有更高的优先级 ,所以当您编写*str[i]您将获得*(str[i]) -第i个字符串的第一个字符。 However, you wanted (*str)[i] . 但是,您想要(*str)[i]

Here are four ways to write what you mean, all of which mean "the i th character of string *str ": 这是四种表达您的意思的方式,所有方式都表示“字符串*stri个字符”:

(*str)[i]
str[0][i]
i[*str]
*(*str+i)

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

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