将数据从.txt读取到数组c ++

时间:2015-08-20 22:05:39

标签: c++ arrays fstream

我对c ++很陌生,基本上我想做的是从.txt文件中检索信息并将这些数据添加到数组中。这是我尝试过的:

string fileName;
string trainArray[20][3];

cout << "\nPlease enter the full file name: ";
cin >> fileName;
int  spaceCount = 0;

ifstream trainFile (fileName,ios::binary);
if (trainFile.is_open()){              
    char ch;
    while(!trainFile.eof()){
        trainFile.get(ch);
        if(ch==' ')
            spaceCount++;
    }
    spaceCount = spaceCount/2;
    cout <<spaceCount;

    for (int i=0; i<=spaceCount; ++i){                    
        trainFile >> trainArray[i][0];
        trainFile >> trainArray[i][1];
        trainFile >> trainArray[i][2];                   
    }
    trainFile.close();
}

这是有效的,因为我检查了文件夹,并使用输入创建了一个新的.txt文件。

这是我的问题,当我尝试从数组中检索数据时,它只会出现一大堆空白空间!这是输出代码:

cout << "\nTHIS IS THE CONTENTS OF THE ROUTE ARRAY: \n" << endl;
for (int i=0;i<spaceCount;i++){
    cout << trainArray[i][0] << " " << trainArray[i][1] << " " << trainArray[i][2] <<endl;
}
cout << endl;

因为txt文件中的数据总是采用这种预设格式:(单词字),每行3个字,因此每行有2个空格。我用一个计数器计算出文档中有多少个空格,然后将其除以2以确定输出循环的次数。我确信有一种更有效的方法可以做到这一点,但这是漫长的一天...我正在考虑搜索'\ n',但是这对于只有一行的文档是有效的,因为不会有一个?

所以我的问题是,如何更改代码以便它实际接收来自.txt文件而不仅仅是空格的数据?

0 个答案:

没有答案