【发布时间】:2020-04-11 05:08:33
【问题描述】:
我正在编写一个 C 程序,它接收一个描述纸牌游戏的文本文件。然后,程序将接受用户在文本文件中描述的一组动作,并通过这些动作来修改游戏的状态。
目前,我正在处理移动,如果有无效移动,我会停止一个 while 循环,并将移动打印到标准错误,格式为“移动 M 是非法的:(移动)”。
char* errString = malloc(sizeof(char) * 10);
errString[9] = '\0';
printString(errString);
int processedMove = 0;
int somethingWrong = 1;
while (processedMove < movesStack.size) {
somethingWrong = processMove(movesStack.cards[processedMove].rank, movesStack.cards[processedMove].suit, &clubsFoundationStack, &diamondsFoundationStack, &heartsFoundationStack, &spadesFoundationStack, &colSevenDown, &colSixDown, &colFiveDown, &colThreeDown, &colFourDown, &colTwoDown, &colOneDown, &colSevenUp, &colSixUp, &colFiveUp, &colThreeUp, &colFourUp, &colTwoUp, &colOneUp, &stockDown, &stockUp, &limitValue, &turnValue);
if (somethingWrong != 1) {
printMove(movesStack.cards[processedMove].rank, movesStack.cards[processedMove].suit, &errString);
printString(errString);
processedMove++;
printf("%d %s\n",processedMove, errString);
fprintf(stderr, "Move %d is invalid %s\n", processed Move, errString);
break;
}
processedMove++;
}
以上是我的主要方法。 printString 将在下面给出,它只是打印给定的字符串。
processMove,取出一摞牌并处理一次走法,如果走法无效则返回-1,如果走法有格式错误则返回-2。
printMove,获取一个等级、花色和一个字符串,并将错误写入给定的字符串,这将在 fprintf 语句中打印。
运行上面的代码后,我留下了这个输出,你可以看到 printString(errString) 的第一次调用,然后是第二次调用,在 errString 被 printMove 函数修改后。最后你会看到 printf 语句,它打印出 processesMove 和 errString 的值。
Commencing the printing of the string with indices
c[0]: h
c[1]: o
c[2]:
Commencing the printing of the string on one line
ho
Commencing the printing of the string with indices
c[0]: 5
c[1]: -
c[2]: >
c[3]: 2
Commencing the printing of the string on one line
5->2
6 5->2
函数 printString
void printString(char* c) {
if (c == NULL) {
printf("string is null\n");
return;
}
printf("\nCommencing the printing of the string with indices\n");
for (int i = 0; i < strlen(c); i++) {
if (c[i] == '\n') {
printf(" c[%d]: newline\n", i);
continue;
}
printf(" c[%d]: %c\n", i, c[i]);
}
printf("Commencing the printing of the string on one line \n");
printf(" ");
for (int i = 0; i < strlen(c); i++) {
if (c[i] == '\n' || c[i] == ' ') {
continue;
}
printf("%c", c[i]);
}
printf("\n");
}
和函数 printMove
void printMove(char f, char s, char** errString) {
char* ret = malloc(sizeof(char) * strlen(*errString));
if (f == '.' && s == '.') {
ret[0] = '.';
ret[1] = '\0';
}
else if (f == 'r' && s == 'r') {
ret[0] = 'r';
ret[1] = '\0';
}
else {
ret[0] = f;
ret[1] = '-';
ret[2] = '>';
ret[3] = s;
ret[4] = '\0';
}
*errString = ret;
}
感谢您的宝贵时间,欢迎提供任何解决方案。
【问题讨论】:
-
您显示的代码不会生成。请edit您的问题包括minimal reproducible example。
-
至于你的问题,你的程序是怎么运行的?在什么环境下?如果您在 IDE 中运行,它可能会将
stderr重定向到其他地方? -
我正在使用Visual Studio,我通过在cmd提示符下编译它来运行它,然后通过命令提示符运行可执行文件,
-
看起来你输出了 3 次,(1)
printString(errString);然后 (2)printf("%d %s\n",processedMove, errString);和fprintf(stderr, "Move %d is invalid %s\n", processedMove, errString);?这是故意的吗? -
printMove函数可能会写越界(不能说没有看到 MTR)
标签: c