gpt4 book ai didi

c - 输入从 A 跳到 B,并在同一行中打印。操作系统C

转载 作者:行者123 更新时间:2023-11-30 20:08:56 29 4
gpt4 key购买 nike

#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:

为什么它会有这样的行为?我为我的英语道歉。

最佳答案

您的程序存在几个问题

  • 你混合了getsscanf("%d"),所以正如备注中所说,你会得到空行
  • 使用gets是危险的,因为没有针对缓冲区溢出的保护,请使用fgets
  • 你说Max。 12 个字符,但实际上是 11 个,因为您需要结尾空字符的位置
  • 您没有检查getsscanf的结果
  • 您没有检查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

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

关于c - 输入从 A 跳到 B,并在同一行中打印。操作系统C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54753490/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com