输入从A跳到B,并且都在同一行中打印。 MacOS C.

问题描述 投票:-2回答:1
#include <stdio.h>
#include <string.h>

int main()
{
  char nameuser[12];
  int userChoice;

  printf("Name(Max. 12 Characters): ");
  gets(nameuser);

  do{
    char messageuser[127];
    FILE *fptr;

    printf("Message: ");
    gets(messageuser);

    fptr = fopen("/Users/exampleuser/Desktop/Test/chat.txt", "a");
    fprintf(fptr, "%s: %s\n", nameuser, messageuser);
    fclose(fptr);

    printf("Another Message? Yes = 1, No = 0: ");
    scanf("%d", &userChoice);
  }while(userChoice == 1);

  return 0;
}

这是我的代码。它适用于GNU / Linux,但不适用于Mac。继承人应该如何运作:

Name: John
Message: Hello Guys!
Another Message? Yes = 1, No = 0: 1
Name... and so on until I stop it.

但这是它在我的Mac上的实际工作方式:

Name: John
Message: Hello Guys!
Another Message? Yes = 1, No = 0: 1
Message: Another Message? Yes = 1, No = 0:

为什么它的行为方式如此?我为我的英语道歉。

c
1个回答
2
投票

您的计划有几个问题

  • 你混合得到和scanf(“%d”)所以在备注中你会得到空行
  • 使用gets是危险的,因为没有防止缓冲区溢出的保护,使用fgets
  • 你说马克斯。 12个字符,但事实上它是11,因为你需要放置结尾的空字符
  • 你不检查gets和scanf的结果
  • 你不检查fopen的结果
  • 当目标是Y / N时,要求0/1并不温和
  • gets(和fgets)在读取时返回\ n但你可能不想要它

以下是考虑到之前评论的建议:

#include <stdio.h>
#include <string.h>

int main()
{
  char nameuser[12];
  int userChoice;

  printf("Name(Max. %d Characters): ", sizeof(nameuser) - 1);
  if (fgets(nameuser, sizeof(nameuser), stdin) == NULL)
    return 0;

  char * p = strchr(nameuser, '\n');

  if (p != NULL)
    *p = 0;

  for (;;) {
    char messageuser[127];

    printf("Message(Max. %d Characters): ", sizeof(messageuser) - 1);
    if (fgets(messageuser, sizeof(messageuser), stdin) == NULL)
      return 0;

    if ((p = strchr(messageuser, '\n')) != NULL)
      *p = 0;

    FILE * fptr = fopen("chat.txt", "a");

    if (fptr == NULL) {
      printf("cannot open file");
      return 0;
    }

    fprintf(fptr, "%s: %s\n", nameuser, messageuser);
    fclose(fptr);

    printf("Another Message? Y/N: ");
    if ((fgets(messageuser, sizeof(messageuser), stdin) == NULL) ||
    (*messageuser != 'Y'))
      return 0;
  }
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra q.c
pi@raspberrypi:/tmp $ rm -f chat.txt
pi@raspberrypi:/tmp $ ./a.out
Name(Max. 11 Characters): me
Message(Max. 126 Characters): this is me
Another Message? Y/N: Y
Message(Max. 126 Characters): and nobody else
Another Message? Y/N: N
pi@raspberrypi:/tmp $ cat chat.txt 
me: this is me
me: and nobody else

注意:我接受空名称和消息,以及开头/结尾的空格,我让你解决这个问题,否则太容易了......

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