C程序不会打印行,已经尝试过刷新

问题描述 投票:0回答:3

该程序应该获取用户的名字和姓氏,然后将它们打印为姓氏,名字。程序在第二次输入后立即停止。我试过fflush(stdout),但这似乎不起作用(我可能做错了)。

#include "stdafx.h"
#include <iostream>
using namespace System;
using namespace std;

int main()
{ 
    char First[30], Last[30];

    printf("Please type in your First Name: ");
    scanf("%s",&First);
    fflush(stdout);

    printf("Please type in your Last Name: ");
    scanf("%s",&Last);

    printf("%s %s", Last, First);

    printf("pause");
    return 0;
}
c visual-studio-2012 printf scanf fflush
3个回答
1
投票

您的程序的C ++版本:

#include <iostream>
using namespace std;

int main()
{ 
  string first, last;

  cerr << "Please type in your First Name: ";
  if (! (cin >> firs))
    return -1;

  cerr << "Please type in your Last Name: ";
  if (! (cin >> last))
    return -1;

  cout << last << ' ' << first << endl;

  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ g++ -pedantic -Wextra i.cc
pi@raspberrypi:/tmp $ ./a.out
Please type in your First Name: aze
Please type in your Last Name: qsd
qsd aze
pi@raspberrypi:/tmp $ 

我检查名称是否输入(没有EOF),我使用cerr确保在不编写endl的情况下刷新消息


而C版:

#include <stdio.h>

int main()
{ 
  char first[30], last[30];

  fprintf(stderr, "Please type in your First Name: ");
  if (scanf("%29s", first) != 1)
    return -1;

  fprintf(stderr, "Please type in your Last Name: ");
  if (scanf("%29s", last) != 1)
    return -1;

  printf("%s %s\n", last, first);

  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra i.c
pi@raspberrypi:/tmp $ ./a.out
Please type in your First Name: aze
Please type in your Last Name: qsd
qsd aze

我限制scanf中的大小不写出数组,我检查scanf能够读取名称,我也使用stderr确保刷新消息而不写'\ n'

第一个和最后一个是数组,在scanf中使用'&'来给出它们的地址是没用的


请注意,这些版本不允许使用空格输入组合名称,以允许读取所有行


0
投票

它有助于考虑fflush()调用的目的。您希望用户看到待处理的数据,以便他们知道要键入的内容。

让我们考虑第一个查询(printf,scanf,flush)。 printf()将数据放入缓冲区。然后scanf()读取用户的响应。在用户输入内容之后才会执行flush()。

这三个电话的顺序错误。我会把这个作为练习给读者留下来。

现在考虑下一个查询(printf,scanf)。 printf()将数据放入缓冲区。 scanf()读取用户的响应,但用户还没有看到“...姓氏:”提示。

显然,该块中也存在错误。再说一遍,我会把这作为读者的练习。提示:如果您修复了第一个应该帮助您理解第二个错误的错误。

顺便说一下,scanf()不会防止First []和Last []数组溢出。这没有必要回答你原来的问题,但我提到它是因为即使修复了代码,它仍然是不安全的。


0
投票

你所拥有的fflush(stdout);并没有帮助,因为它在代码中太早了,因为它无法帮助刷新后面的printfs。您也可以使用\n进行冲洗。但是,如果您的输出设备不是交互式设备,则可能无效。重定向到文件。

你还有scanf()格式说明符的另一个问题:FirstLast,是数组,当传递给scanf时会衰减为指针。所以你将错误类型的参数传递给scanf - 只需从scanf调用中删除&

所以你的程序可能只是:

#include <stdio.h>

int main(void)
{ 
    char First[30], Last[30];

    printf("Please type in your First Name: ");
    scanf("%s", First);
    fflush(stdout);

    printf("Please type in your Last Name: ");
    scanf("%s", Last);
    fflush(stdout);

    printf("%s %s\n", Last, First);
    fflush(stdout);

    getchar();
    return 0;
}

如果您可以在所有printf调用中使用fflush(stdout),则可能不需要所有\n调用,因为您可能使用交互式终端。

如果您使用的是C ++,那么您应该使用iostream进行I / O操作。如果没有别的,scanf is a terrible, has many problems, and should be avoided

© www.soinside.com 2019 - 2024. All rights reserved.