在C中使用fprintf打印到stderr

  • 本文关键字:打印 stderr fprintf c
  • 更新时间 :
  • 英文 :


我正在编写一个C程序,该程序接收一个描述纸牌游戏的文本文件。然后,该程序将接受用户在文本文件中描述的一组动作,并完成这些动作,修改游戏状态。

目前,我正在处理移动,如果有无效的移动,我会停止while循环,并以"移动M是非法的:(移动("的格式打印到标准错误。

char* errString = malloc(sizeof(char) * 10);
errString[9] = '';
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 %sn",processedMove, errString);
fprintf(stderr, "Move %d is invalid %sn", processed Move, errString);
break;
}
processedMove++;
}

以上是我的主要方法。printString将在下面给出,它只是打印给定的字符串。

processMove,获取牌堆并处理一个移动,如果移动无效,则返回-1,如果移动有格式错误,则返回-2。

printMove,获取一个rank、and suit和一个字符串,并将错误写入给定的字符串,这将在fprintf语句中打印出来。

运行完上面的代码后,我得到了这个输出,您可以看到printString(errString(的第一个调用,然后是printMove函数修改errString后的第二个调用。最后,您可以看到printf语句,它打印processedMove和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 nulln");
return;
}
printf("nCommencing the printing of the string with indicesn");
for (int i = 0; i < strlen(c); i++) {
if (c[i] == 'n') {
printf("        c[%d]: newlinen", i);
continue;
}
printf("        c[%d]: %cn", 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] = '';
}
else if (f == 'r' && s == 'r') {
ret[0] = 'r';
ret[1] = '';
}
else {
ret[0] = f;
ret[1] = '-';
ret[2] = '>';
ret[3] = s;
ret[4] = '';
}
*errString = ret;
}

感谢您抽出时间,欢迎任何解决方案。

所以这里的问题是,不能在stderr的流中使用自己的变量。

最新更新