首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

文件读取数组有关问题,求高手帮看看

2012-04-12 
文件读取数组问题,求高手帮看看C/C++ codeLINES2 CountLines(filename2)string *s1 new string[LINES2

文件读取数组问题,求高手帮看看

C/C++ code
        LINES2 = CountLines(filename2);        string *s1= new string[LINES2];        string *s2= new string[LINES2];        int k = 0;        while (!file2.eof())         {                                 //读取数据到数组            if (k>=LINES2)            {                  cout << "文件最后一行存在空格,程序退出!" << endl;                system("pause");            }            getline(file2, s1[k], ' ');            getline(file2, s2[k], '\n');            k++;        }


我的txt文档类似如下

ABC1 DDDD DDDD DDDD
ABC2 DDD DDD DDDDDDDD
ABC3 DDDDDDDD DDDDDD

第一个数组读取ABC 第二个数组读取后面的DDDDD

那位朋友能帮我修改下?
如果我用getline(file2, s2[k], '\n');
有时候会出错

[解决办法]
错误的原因是第二次getline没有判断file2.eof()
[解决办法]
看你的代码看不出来错,最好调试一下看看哪儿出的错
[解决办法]
string不要用new的形式,。。。
[解决办法]
if (k>=LINES2) 之后没有退出while循环阿,加个break
C/C++ code
            if (k>=LINES2)            {                  cout << "文件最后一行存在空格,程序退出!" << endl;                system("pause");                break;            }
[解决办法]
C/C++ code
#include <iostream>#include <fstream>#include <string>using namespace std;int CountLines(string filename){    ifstream fin;    fin.open(filename.c_str());    char* buff= new char[1024];    int count = 0;    while (!fin.eof())    {        fin.getline(buff, 1024);        count ++;    }    delete buff;    fin.close();    return count;}int main(void){    string filename = "D:\\workspace\\test1\\my.txt";    ifstream fin;    fin.open(filename.c_str());    if (fin.bad())    {        return 0;    }    int LINES2 = CountLines(filename);    string *s1= new string[LINES2];    string *s2= new string[LINES2];    int k = 0;    while (!fin.eof())     {                                 //读取数据到数组        getline(fin, s1[k], ' ');        getline(fin, s2[k], '\n');        k++;    }    for(int i = 0; i < LINES2; i++)    {        cout << s1[i] << s2[i] << endl;    }    delete []s1;    delete []s2;    return 0;}
[解决办法]
恭喜楼主 找见问题 学习..........

热点排行