将两个单词读入一个char数组元素

时间:2014-09-16 00:15:06

标签: c++

我试图将两个单词从文本文件读入一个char数组元素。我不能使用std :: string。我得到一个seg错误,因为我的循环以超出范围的方式循环。我无法复制这两个字。请帮我这个!!我的卡片结构循环完美无缺。我无法将“最后一个”带入人民[]。姓名     //一副牌     //下面是初始化     #包括     #包括     #包括     #包括     #include

using namespace std;

//globals
const int maxCards = 52;

//Structs
struct card {
char suit[8];
char rank[6];
int cvalue;
char location;
};

struct player {
char name[100];
int total;
card hand[4];
};

//program
int main()
{

//constants

char tempfName[100];
char templName[100];

//create struct array(s)
card deck[52];
card shuffledDeck[52];
player people[4];

//create pointers
card * deckPointer =NULL;
deckPointer = deck;
card * shuffledDeckPointer=NULL;
shuffledDeckPointer = shuffledDeck;

for(int i=0;i<4;i++)
    {
    strcopy(people[i].name,"first last");
    }

//open player names file
ifstream fin2;
string fin2Name;

//get file name from user
cout << "Enter player file name...(Players.txt)" << endl;

getline(cin, fin2Name);

//open file
fin2.open(fin2Name.c_str());

//check if Players.txt opens correctly
if(!fin2.good())
    {
    cout << "Error with player file!" << endl;
    return 0;
    }
else
    {

    int j =0;
    fin2 >> people[j].name;  //prime file
    while(fin2.good())
    {
    //find the length
    int index =0, length=0;
        while(tempfName[length] != '\0')
        {
            length++;
        }
    //now add space after first name
    tempfName[length] = ' ';
    length++;
    while(templName[index] != '\0')
    {
        tempfName[length] = templName[index];
        length++;
        index++;
    }
    tempfName[length]='\0';
    int counter =0;
    while(templName[counter] != '\0')
    {
    people[0].name[counter] = templName[counter];
    counter++;
    }
}
        }

2 个答案:

答案 0 :(得分:0)

你可以做一些作弊:

  char full_name[256]; // Binary quantities are better.
  snprintf(full_name, sizeof(full_name),
           "%s %s",
           first_name, last_name);

您应该对C风格的字符串函数进行更多研究,例如查看一本好的参考书。它应该有一章关于C风格的字符串函数。

以下是一些有用的内容:
strcpy, strcat, strchr, sprintf, strlen

答案 1 :(得分:0)

似乎你的tempfName没有指向else语句中while循环中的正确对象 其他     {

int j =0;
fin2 >> people[j].name;  //prime file
while(fin2.good())
{
//find the length
int index =0, length=0;
    while(tempfName[length] != '\0')
    {
        length++;
    }