如何从文件中读取文本行,并把它们放到一个数组 [英] How to read lines of text from file and put them into an array
本文介绍了如何从文件中读取文本行,并把它们放到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建一个文本文件 love.txt
:
我爱你
你爱我
我如何保存它们到单独的阵列,即行1
和 2号线
,然后在控制台显示出来?
的#include<&iostream的GT;
#包括LT&;&的fstream GT;
#包括LT&;串GT;
使用命名空间std;诠释的main()
{
串行1 [30];
2号线串[30];
ifstream的MYFILE(love.txt);
INT A = 0;
INT B = 0;
如果(!MYFILE)
{
COUT<<错误打开输出文件<< ENDL;
系统(暂停);
返回-1;
}
而(!myfile.eof())
{
函数getline(myfile的,第1行[一个],'');
COUT<<1。<<一号线[A] - LT;<\\ n;
函数getline(myfile的,第2行并[b],'');
COUT<<2。<< 2号线[B]<<\\ n;
}
}
解决方案
尝试指定的最后一个参数为的'\\ n'在两个函数getline()
功能:
函数getline(MYFILE,一号线[A]的'\\ n');
而不是
函数getline(MYFILE,一号线[A],'');
I created a text file love.txt
:
i love you
you love me
How do I store them into separate array, namely line1
and line2
and then display them out in console?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line1[30];
string line2[30];
ifstream myfile("love.txt");
int a = 0;
int b = 0;
if(!myfile)
{
cout<<"Error opening output file"<<endl;
system("pause");
return -1;
}
while(!myfile.eof())
{
getline(myfile,line1[a],' ');
cout<<"1."<<line1[a]<<"\n";
getline(myfile,line2[b],' ');
cout<<"2."<<line2[b]<<"\n";
}
}
解决方案
Try specifying the last argument as '\n' in both getline()
functions:
getline(myfile, line1[a], '\n');
instead of
getline(myfile, line1[a], ' ');
这篇关于如何从文件中读取文本行,并把它们放到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文