#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:
为什么它的行为方式如此?我为我的英语道歉。
您的计划有几个问题
以下是考虑到之前评论的建议:
#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
注意:我接受空名称和消息,以及开头/结尾的空格,我让你解决这个问题,否则太容易了......