我正在 Ubuntu 中使用 GCC 制作一个小型 ANSI C 应用程序,这需要使用 strcpy()。
我的头文件:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define DECKSZ 52
typedef struct card {
enum {ACE=1, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING} pips;
enum {SPADES, CLUBS, HEARTS, DIAMONDS} suit;
char cardName[20];
} card;
extern card deck[];
void initDeck(card[]);
void labelCards();
void shuffleDeck(card[]);
void swap(card*,card*);
我的主文件:
#include "CardOps.h"
card deck[DECKSZ];
void initDeck(card deck[]) {
int counter;
for (counter = 0; counter < DECKSZ; counter++) {
deck[counter].pips = (const)((counter % 13) + 1);
deck[counter].suit = (const)(counter / 13);
}
}
void labelCards(card deck[]) {
static const char *pipNames[] = {"Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"};
static const char *suitNames[] = {"Spades","Hearts","Diamonds","Clubs"};
int i;
for (i = 0; i < DECKSZ; i++) {
strcpy(deck[i].cardName, pipNames[i]);
/*strcpy(cardName, suits[i]);*/
}
}
int displayCards(card deck[], int numCards) {
int i, countCards;
if (numCards > 52)
countCards = 52;
else
countCards = numCards;
for (i = 0; i < countCards; i++) {
printf(deck[i].cardName);
}
return countCards;
}
void shuffleDeck(card deck[]) {
int i, j;
for (i = 0; i < DECKSZ; i++) {
j = rand() % DECKSZ;
swap(&deck[i], &deck[j]);
}
}
void SortCards() {
}
void swap(card *c1, card *c2) {
card temp;
temp = *c1;
*c1 = *c2;
*c2 = temp;
}
int main(void) {
initDeck(deck);
/*labelCards(deck);*/
displayCards(deck,52);
shuffleDeck(deck);
return EXIT_SUCCESS;
}
我在让 strcpy() 在我的 labelCards() 函数中工作时遇到了问题。有人可以帮我 strcpy() 吗?谢谢!
最佳答案
我认为使用 sprintf
比使用 strcpy
更好。这是因为 sprintf
返回一个整数,告诉您写入目标缓冲区的字符数。有了这些知识,您就知道在写西装时从哪里开始写了。
//copy the name into the buffer at cardname
int written = sprintf(deck[i].cardName, "%s" pipNames[i%13]);
//copy the suit name into the same buffer, but advanced by however many chars we just wrote
sprintf(deck[i].cardName + written, "%s", suits[i/13]);
现在它会说 FiveHearts 和 AceClubs 之类的东西......不是最优的,但你可以从这里开始工作。
编辑:user3386109 提出了一种比我的更聪明的方法:
sprintf(deck[i].cardName, "%s of %s", pipNames[i%13], suits[i/13] );
一个 sprintf
肯定比我做的两个要好。在某些情况下,知道如何从使用 sprintf
中断的地方继续编写是很有值(value)的,但这不是其中之一。我还根据 user3386109 的修改更正了 pipNames
和 suit
中索引的逻辑。
关于c - 如何使用 strcpy 将字符串数组存储到结构中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22568077/