如何创建输入循环?

时间:2015-05-15 01:04:36

标签: c loops input

我正在寻找一种方法来编写一个输入循环,继续打印提示,直到用户输入一个空行。

这就是我想要做的事情:

循环启动,将提示符>打印到命令行。用户输入以'\ n'结尾的行,我的程序对该行执行任何操作,然后再次打印>。这一直持续到用户输入一个空行(\n),此时循环终止。

2 个答案:

答案 0 :(得分:2)

这些方面有什么能满足你的需求吗?

int ret;
// Basically, in order, 1 to indicate the file descriptor of the standard output
// ">" as the string you want to print
// 1 as the number of characters you want printed.
write(1, ">", 1);
while ((ret = read(0, buff, SizeBuff)) > 0) {
    buff[ret] = 0;
    if (buff[0] == '\n' && strlen(buff) == 1)
        return (0);
    /*Do your stuff*/
    write(1, ">", 1);
} 

答案 1 :(得分:1)

也可以使用非常简单的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通过动态分配行缓冲区,只要您想要提供它就可以接受一行。它可以是数十亿个字符(达到你记忆的程度)。这是一种力量和弱点。如果您需要限制接受的数据量,则由您来检查/验证/ etc ....

#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))。

的#include     #include

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 .......... ............. .............)
 >