从.txt读取两个字符串和int到struct数组中

时间:2014-09-08 23:20:33

标签: c++ arrays struct

我试图读取套装,等级和卡片价值(例如:来自文本文件的7号心脏和#34;并将其输入结构。下面的代码概述了我要做的事情,只是我没有正确实现它。我的问题是:如何修复我的循环以增加我的文本文件,并将套装分配给:deck [0] .suit,deck [0] .rank和deck [0 ] .cvalue到甲板[51]。我能够正确循环并将值分配给一个数组,但现在我卡住了。我也不能得到两个c风格的字符串和int值正确地复制到数组谢谢你的帮助!

// deck of cards
// below are initializations
#include <iostream>
#include <fstream> 
#include <ctime>
#include <stdlib.h>

using namespace std;
//globals
const int maxCards = 52;

//Structs
struct card {
    char suit;
    char rank;
    int cvalue;
    char location;
};

struct player {
    char name;
    int total;
    char hand[3];
};

int main()
{

    //seed the time
    srand(time(NULL));

    //constants

    bool gameOn =true;
    int choice;
    char tempSuit;
    char tempRank;
    int tempValue;

    struct card deck[51];
    int count = 0;
    int index = 0;
    ifstream myfile ("cardFile.txt"); //read cards from .txt

    if(!myfile.good())
    {
        cout << "Your .txt data file did not load         correctly" << endl;
        system ("pause");
        return 0;
    }
    else
    {
        myfile >> tempRank;
        myfile >> tempSuit;
        while(myfile.good())
        {
            int index=0;
            int length=0;
            int cvhold;
            int i = 0;
            while (tempRank[length] != '\0')
            {            
                length++;
            }
            deck[i].rank = tempRank[length];
            length ++;
            while(tempSuit[index] !='\0')
            {
                tempRank[length] = tempSuit[index];
                length++;
                index++;
            }
            deck[i].suit = tempRank[length];
            length++;
            i++;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

首先,如果您在示例中使用了文本文件的模板:

 heart seven 7
 spade six 6
 ..etc

然后,您的struct card元素char suit; char rank;无法保存字符串的值&#34; heart&#34;,&#34; seven&#34;等

至于阅读价值观。您已经知道数量(52 = maxCards),您可以使用for-loop

for (int i = 0; i < maxCards; ++i)                                                                                                                                        
{
    myfile >> deck[i].suit;
    myfile >> deck[i].rank;
    myfile >> deck[i].cvalue;
}

其中,我假设您已将struct card修改为:

struct card
{
     std::string suit;
     std::string rank;
     int cvalue;
     char location;
};