首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

从txt文件中读取一起字符串

2013-10-14 
从txt文件中读取一行字符串如题目所示,就是从指定的txt文档中读取出一行文字,然后输出。#includestring#i

从txt文件中读取一行字符串
如题目所示,就是从指定的txt文档中读取出一行文字,然后输出。


#include<string>
#include<iostream>
#include<fstream>

using namespace std;

ifstream& open_file(ifstream &in,const string &file)
{
in.close();
in.clear();
in.open(file.c_str());
return in;
}


int main()
{
ifstream infile;

string textname;
string temp;
vector<string> ivec;
printf("请输入语句所在的文件名:\n");
scanf("%s",textname);

open_file(infile,textname);
getline(infile,temp);
cout<<temp<<endl;

}

代码就是上面这样,但是调试时会出现内存异常的问题。
求解。
[解决办法]
scanf("%s",textname);

改为
std::cin >> textname;

[解决办法]

#include<string>
#include<iostream>
#include<fstream>
#include <vector>//楼主你这里少了这个头文件,都不知道你这样还能编译,调试异常?

using namespace std;

ifstream& open_file(ifstream &in,const string &file)
{
in.close();
in.clear();
in.open(file.c_str());
return in;
}


int main()
{
ifstream infile;

string textname;
string temp;
vector<string> ivec;
printf("请输入语句所在的文件名:\n");
//scanf("%s",textname);//scanf在这里的话会提示警告,而且scanf你用的是ms 的编译器VS的话就是被认为不是安全的函数
        cin>>textname;
open_file(infile,textname);
getline(infile,temp);
cout<<temp<<endl;
  return 0;//下面没有返回!!
}
楼主你直接将我这个程序复制粘贴就可以运行!
记得给我分哦!我穷死了!!,没有帮人回答过问题!!哈哈

热点排行
Bad Request.