我创建了一个文本文件love.txt:
i love you
you love me
Run Code Online (Sandbox Code Playgroud)
如何将它们存储在独立的阵列,即line1和line2,然后在控制台显示出来?
#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";
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
这个怎么样.. 。
vector <string> v;
string line;
ifstream fin("love.txt");
while(getline(fin,line)){
v.push_back(line);
}
Run Code Online (Sandbox Code Playgroud)
尝试在两个函数中将最后一个参数指定为'\n'getline():
getline(myfile, line1[a], '\n');
Run Code Online (Sandbox Code Playgroud)
代替
getline(myfile, line1[a], ' ');
Run Code Online (Sandbox Code Playgroud)