逐行读取文件,并将数据插入变量和数组中

Read a file line by line and insert data in to variables and arrays

本文关键字:变量 插入 数组 数据 读取 文件 逐行      更新时间:2023-10-16
VA3012020年2月20日10:20科伦坡新加坡10 E AB15 E CDE22 E ADF31亿立方英尺35 E ABCD45 E AB50 E DEF

这些是我的文件中的详细信息。我想逐行读取这个文件,并将前5行存储到一个变量中,将其他行存储到3个字符数组中。

我不知道你为什么真的想这么做。如果你能给我更好的解释,我就能给你更好的答案。

若要读取表单文件,您必须使用文件流输入。示例:

ifstream infile("thefile.txt");// change thefile to your file name and make sure it's at the same folder with the programe

现在可以使用getline()方法从流中获取数据。

string line;
char ch[200];
getline(infile, line);//this to store the line into a string
getline(infile,line,'&'); // the last parameter is the "delimiter"
//getline() will use delimiter to decide when to stop reading data.
infile.getline(ch,200);  //this to store the line into a char array

只需使用循环和eof()方法即可读取文件的

while (infile.eof( ))//Mean read until the end of file
{
//do something 
}

把所有东西放在一起:

#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream infile("thefile.txt");// change thefile to your file name and make sure it's at the same folder with the programe
string line, var="";
while (infile.eof( ))//Mean read until the end of file
{
getline(infile, line);//this to store the line into a string
var= var + line +'n';
}
//assuming that they are just 3 other lines
char ch1[200],ch2[200],ch3[200];//you can choose another size
infile.getline(ch1,200);
infile.getline(ch2,200);
infile.getline(ch3,200);
}

有关更多信息,您可以阅读:https://en.cppreference.com/w/cpp/string/basic_string/getlinehttps://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm