c - 用户输入未被识别,但如果最初设置了数字则程序可以运行

标签 c unix fork pipe scanf

这个问题我已经研究了好一阵子了。我将打印出双“生成”,它显然是用户输入的数字,但由于某种原因,它的行为方式不同。顺便说一句,这是在 Unix 上。

double generate;
int child1, child2, retval, first, second, next, c;
//generate = 10;
first = 1;
second = 1;

retval = pipe (pfd);

if (retval != 0 ) {
    fprintf(stderr, "Pipe failed\n");
    exit(0);
}

printf("Enter the number of Fibinachi numbers you'd like to generate: \n");
scanf("%d", &generate);
//printf("%d\n", generate);

child1 = fork();

if(child1 == 0)
{
    child2 = fork();

    if(child2 == 0)
    {
        printf("Im the child child \n");
        for ( c = 0; c < generate; c++ )
        {
            if ( c <= 1 )
                next = 1;
            else
            {
                next = first + second;
                first = second;
                second = next;
            }
            write (pfd[WRITE_END], &next, sizeof(int));
        }
    }
    else
    {
        printf("Im the child \n");
        FILE * Output;
        Output = fopen("data.txt", "w+");

        for ( c = 0; c < generate; c++ )
        {
            read(pfd[READ_END], &next, sizeof(int));
            fprintf(Output, "%d\n", next);

            printf("%d\n", next);
            wait(NULL);
        }
    }
}
else
{
    printf("Hey, I am the Parent.\n");

}

exit(1);

最佳答案

使用 %lf 读取 double 型变量。

双生成;

scanf("%d", &generate); --> scanf("%lf", &generate);

如果变量像 generate = 10; 这样初始化,那么它被认为是 generate = 10.0; 并且工作正常。

关于c - 用户输入未被识别,但如果最初设置了数字则程序可以运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21870920/

相关文章:

c - 为什么在这段代码中没有打印任何换行符时缓冲区被刷新?

c - 你怎么能 "avoid"SIGSEGV?

c - 多维数组 : printing addition table in C

Bash - 如何以字节为单位列出文件大小

regex - Grep for <?php 空行后

c - 为什么权限参数会影响我的小型测试程序中写入文件的内容?

用于读取测试结果的 C 程序

c - 将 fork 与 setjmp/longjmp 结合使用

c - 分析多进程程序

c++ - 如何从本地目录加载 C++ 中的图像