也可以使用很简单的scanf版本:
#include <stdio.h>
#define MAXL 64
int main (void) {
char str[MAXL] = {0};
printf ("\n Enter a string ([enter] alone to quit)\n");
while (printf (" > ") && scanf ("%63[^\n]%*c", str) == 1)
{
/* do whatever in your code */
printf (" result: %s\n", str);
}
return 0;
}
使用/输出
$ ./bin/scanf_enter_quits
Enter a string ([enter] alone to quit)
> string
result: string
> another
result: another
>
注意: MAXL-1 添加为 scanf 的最大宽度说明符,以防止写入超出数组末尾。
getline 示例
getline 通过动态分配行缓冲区允许你接受一行,只要你想给它。它可以是数十亿个字符(取决于您的记忆范围)。这是一个优势和一个弱点。如果您需要限制您接受的数据量,则由您来检查/验证/等....
#include <stdio.h>
#include <stdlib.h>
int main (void) {
char *str = NULL;
size_t n = 0;
ssize_t nchr = 0;
printf ("\n Enter a string ([enter] alone to quit)\n");
while (printf (" > ") && (nchr = getline (&str, &n, stdin)) > 1)
{
str[--nchr] = 0; /* strip newline from input */
printf (" (str: %s)\n", str); /* do whatever in your code */
}
if (str) free (str);
return 0;
}
使用/输出
$ ./bin/getline_enter_quits
Enter a string ([enter] alone to quit)
> string one as long as you want
(str: string one as long as you want)
> string 2 make it 1000 chars.........................................
(str: string 2 make it 1000 chars.........................................)
>
scanf动态分配
您还可以让scanf 使用m 转换说明符为您动态分配空间(scanf 的旧版本为此使用a 转换说明符)。在这种情况下,您还必须提供 pointer-to-pointer 以接受该地址。 (例如scanf ("%m[^\n]%*c", &str))。
#包括
#包括
int main (void) {
char *str = NULL;
printf ("\n Enter a string ([enter] alone to quit)\n");
while (printf (" > ") && scanf ("%m[^\n]%*c", &str) == 1)
{
printf (" (str: %s)\n", str); /* do whatever in your code */
if (str) free (str); /* you must free each loop */
str = NULL;
}
if (str) free (str);
return 0;
}
使用/输出
$ ./bin/scanf_dyn_enter_quits
Enter a string ([enter] alone to quit)
> some string as long as you want
(str: some string as long as you want)
> another string any length .......... ............. .............
(str: another string any length .......... ............. .............)
>