getline 的使用
我想根据输入的路径,打开这个文件。程序如下。可是如果输入F:\zl.txt就可以读出。但是要是输入f:\My Documents\zl.txt就无法读出。有高手指点说用getline(cin,filepath),可是我不会把输入压入vector,以实现程序其他功能。请高手继续指点。谢谢
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
vector<string> words;
string filepath;
cout<<"请输入文件的路径,像F:\\zl.txt" <<endl;
cin >> filepath;
ifstream in(filepath.c_str());
while(in >> receives) //读入.in >> receives
words.push_back(receives); //把每个单词存到vector里面
}
问题点数:50、回复次数:4Top
1 楼zoohoo(zoohoo)回复于 2003-11-01 10:06:49 得分 5
char buf[1024];
ifstream in(filepath.c_str(), ios::in);
if(in.bad() || !in.good())
{
cout << "Open file error\n";
}
else
{
in.getline(buf, sizeof(buf));
words.push_back(string(buf));
}
Top
2 楼ttlb(__ttlb__ttlb__小鸟)回复于 2003-11-01 13:03:58 得分 35
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
vector<string> words;
string filepath;
cout<<"请输入文件的路径,像F:\\zl.txt" <<endl;
cin >> filepath;
ifstream in(filepath.c_str());
string str;
while(getline(in, str, '\0')) //读入.in >> receives
words.push_back(str); //把每个单词存到vector里面
}
Top
3 楼langzi8818(┤天道酬勤┝爱老婆┦┷我是来学习滴┷)回复于 2003-11-01 13:20:11 得分 5
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
vector<string> words;
string filepath;
cout<<"请输入文件的路径,像F:\\zl.txt" <<endl;
cin >> filepath;
ifstream in(filepath.c_str());
string words;
while(in >> words) //读入.in >> receives
words.push_back(receives); //把每个单词存到vector里面
}
Top
4 楼ywchen2000(灌水大帝:努力奋斗)回复于 2003-11-01 21:49:38 得分 5
include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
vector<string> words;
string filepath;
cout<<"请输入文件的路径,像F:\\zl.txt" <<endl;
cin >> filepath;
ifstream in(filepath.c_str(),ios::in);
string str;
while(getline(in, str, '\0')) //读入.in >> receives
words.push_back(str); //把每个单词存到vector里面
}
Top



