我有:
char *card[4];
gets(&card[player - 1]); // 2 chars at a time (e.g. 2S, 3D, TF)
我可以通过以下方式打印字符串:
printf("%s",&card[0]);
但是如何从 &card[0]
获取每个字符(例如 '2'
和 'S'
)?
最佳答案
只需对它们进行索引即可。例如:
printf("%c %c", card[0][0], card[0][1]);
但是,您的示例代码是错误的(没有分配内存并获取调用gets
的地址)。
相反,请执行以下操作:
#define NPLAYERS 5
#define LENGTH 3 // 2 + the null terminator
char card[NPLAYERS][LENGTH];
int player = 0; // first player
fgets(card[player], LENGTH, stdin);
printf("%c %c", card[player][0], card[player][1]);
这为 5 个玩家保留了空间,每个玩家都有一个可容纳 3 个角色的缓冲区。总共 15 个字节。
最好检查一下fgets
的返回码。
关于c - 如何获取字符串中的每个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58035324/