文件读取数组问题,求高手帮看看
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++; } if (k>=LINES2) { cout << "文件最后一行存在空格,程序退出!" << endl; system("pause"); break; }
[解决办法]
#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;}
[解决办法]
恭喜楼主 找见问题 学习..........