简体   繁体   English

如何在C中的scanf()函数中使用无限类型说明符?

[英]How to use infinite type specifiers in scanf() function in C?

I want to use infinite type specifiers (%c) in scanf() function. 我想在scanf()函数中使用无限类型说明符(%c)。

For example- 例如-

printf("Enter characters: \t");
scanf("--SPECIFIERS--");

So its not definite how much characters the user will enter. 因此,不确定用户将输入多少个字符。 I don't want my program to ask the user the 'numbers of characters'.. but I want to allow any the numbers of characters. 我不想让我的程序问用户“字符数” ..但是我想允许任何字符数。 But its not possible to enter infinite %c in scanf(). 但是不可能在scanf()中输入无限的%c。 Can anyone tell me how to do that in C? 谁能告诉我如何用C做到这一点?

I want to use infinite type specifiers (%c) in scanf() function. 我想在scanf()函数中使用无限类型说明符(%c)。

You want to read an unspecified amount of data. 您想要读取未指定数量的数据。 There are a few approaches you can try: 您可以尝试以下几种方法:

  • Use the POSIX standard getline(3) function 使用POSIX标准getline(3)函数
  • Use the POSIX standard m assignment-allocation in the scanf() family of functions scanf()系列函数中使用POSIX标准m分配-分配

     char *str; scanf("%m[^\\n]", &str); 
  • Read input one char at a time and grow a buffer as you go. 一次读取输入的一个字符,并随行增加一个缓冲区。 There are a few functions floating about on stackoverflow, doing just this 在stackoverflow上有一些浮动的函数,就是这样做的

The first 2 also allocate memory which you should free(3) . 前2个还会分配您应该free(3)内存。

Use %s as qualifier for scanf . %s用作scanf限定符。 The one mentioned as below: 一个提到如下:

scanf("%s",buf);

where buf is of type: 其中buf类型:

char buf[100];

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

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