逐行读取文件,并将数据插入变量和数组中
Read a file line by line and insert data in to variables and arrays
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
相关文章:
- 如何在变量中插入多种不同长度的数据类型?
- 逐行读取文件,并将数据插入变量和数组中
- 在 std::map 中插入对象时构造函数中变量的地址
- 如何在Qt cpp的SQlite数据库中插入变量的值
- 如何通过 C 变量将数据插入表中
- 在变量中插入值
- 如何将变量插入C++
- 正在使用C 中的插入后变量不确定行为访问数组的元素
- 将变量插入到 mysql 表中
- 从.txt文件中读取一行,然后插入变量
- 将变量插入到 SQLite 查询
- 多个布尔表达式,而不重新插入变量
- 在文件名中插入int变量
- 如何将变量类型作为参数函数插入
- 如何将变量插入到创建目录()
- (C++中的 SQL)如何插入变量
- 从文本文件中提取特定值(char & int)并插入到多个变量中C++
- 如何在std::string中插入无符号char*变量
- 如何在字符*中插入变量的值
- 插入MySQL命令和C++变量