C++里,读取一个txt文件里的某一行,然后将这一行里的每一个字符串(用空格隔开的)存到数组里

C++里,我想读取一个txt文件里的某一行(例如我想读取第三行),然后将这一行里的每一个字符串(用空格隔开的)存到数组里供调用,求具体代码或者例程,本人刚开始学习,请大虾指教,谢谢!附上txt文本

#include <iostream>

#include <fstream>

#include <string>

using namespace std;


#define FILE_NAME "file.txt"


void readfile(double arr[], int len, int line)

{

if (len<1 || line <1)

return;

int i = 0, j = 0;

int s = 0;

int h=0,t=0;

string str;

char buf[512];

char *p = NULL;

ifstream file(FILE_NAME, ios::in);

if(!file)

cout <<"error!"<<endl;

for(i=1; i<line;i++)

file.getline(buf,512);

memset(buf,0,512);

file.getline(buf,512);


while(buf[j] != '=')

j++;

while(buf[j] == '='|| buf[j] == ' ')

j++;

p = &buf[j];

str = p;

while(t != -1)

{

if (s>len-1)

return;

t = str.find(' ', h);

if (t == -1){

return;

}else if(t == 1){

h = t+1;

continue;

}else{

arr[s++] = atof(str.substr(h,t-h).c_str());

}

h = t+1;

}

cout << str<<endl;


}


int main()

{

double a[5];

readfile(a,5,3);

cout <<a[0]<<" "<<a[1]<<" "<<a[2]<<" "<<a[3]<<" "<<a[4]<<endl;

return 0;

}

使用说明:一,宏定义FILE_NAME定义要读的文件全路径。二,readline()函数的参数,arr指要存放数据的数组,len指数组大小,line指要读取的行号

亲测可用,有不懂的可再问我

满意请采纳。

温馨提示:答案为网友推荐,仅供参考
相似回答
大家正在搜