c++逐行读取txt文件出现问题
#include<fstream>#include<string>#include<iostream>usingnamespacestd;intmain(){ifstre...
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
ifstream in("test.txt");
string filename;
string line;
int a = 4;
string *str;
str = new string[a];
int counter = 0;
if (in)
{
while (getline(in, line))
{
cout << line << endl;
str[counter] = line;
counter++;
}
}
else
{
cout << "no such file" << endl;
}
for (int i = 0; i < 4; i++)
{
cout << "第" << i+1 << "行:" << str[i] << endl;
}
return 0;
}
这个是可以正常读取的
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string *getdate(string a,int b)
{
ifstream in(a);
string line;
string *temp=new string[b];
int count = 0;
if (in)
{
while (getline(in, line))
{
cout << line << endl;
temp[count-1] = line;
count++;
}
}
else
{
cout << "no such file" << endl;
}
return temp;
}
int main()
{
string *str;
int a=4;
str = new string[a];
str = getdate("test.txt",a);
for (int i = 0; i < a; i++)
{
cout << "第" << i+1 << "行:" << str[i] << endl;
}
return 0;
}
但写成函数型式就不能读取了是什么原因 展开
#include <string>
#include <iostream>
using namespace std;
int main()
{
ifstream in("test.txt");
string filename;
string line;
int a = 4;
string *str;
str = new string[a];
int counter = 0;
if (in)
{
while (getline(in, line))
{
cout << line << endl;
str[counter] = line;
counter++;
}
}
else
{
cout << "no such file" << endl;
}
for (int i = 0; i < 4; i++)
{
cout << "第" << i+1 << "行:" << str[i] << endl;
}
return 0;
}
这个是可以正常读取的
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string *getdate(string a,int b)
{
ifstream in(a);
string line;
string *temp=new string[b];
int count = 0;
if (in)
{
while (getline(in, line))
{
cout << line << endl;
temp[count-1] = line;
count++;
}
}
else
{
cout << "no such file" << endl;
}
return temp;
}
int main()
{
string *str;
int a=4;
str = new string[a];
str = getdate("test.txt",a);
for (int i = 0; i < a; i++)
{
cout << "第" << i+1 << "行:" << str[i] << endl;
}
return 0;
}
但写成函数型式就不能读取了是什么原因 展开
1个回答
展开全部
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string *getdate(char *a,int b){//这里把string a改成char *a,因下一句要求()里是char*
ifstream in(a);
string line;
string *temp=new string[b];
int count = 0;
if(in){
while(getline(in, line),count<b){//这里加一句count<b控制循环结束
cout << line << endl;//这里输出有必要吗?尽量不要在函数数中搞输出
temp[count] = line;//这里把count-1改count,不然第一次是-1而非法
count++;
}
}
else
cout << "no such file" << endl;
return temp;
}
int main(void){
string *str;
int a=4;
//str = new string[a];这一行删除,不然有引起内存泄漏之嫌
str = getdate("test.txt",a);
for(int i = 0; i < a; i++){
cout << "第" << i+1 << "行:" << str[i] << endl;
}
delete []str;//不释放申请的空间能行吗?
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询