在C++社区里看到的一道笔试题,自己用STL实现了一下,遇到一个文件操作方面的问题:
void f(const ifstream &fin)
{
char ch = fin.get(); // 这样会出错,如果去掉const就不会出错
}
现在还弄不明白怎么会这样.
/**/
/*
比如文件file.txt中存放的是单词
单词使用空格,逗号和点分隔,
若文件中是I don 't know you don 't know I know
则要输出
don 't
i
know
you
也就是需要对单词排序,没搞定这道垃圾题
考查知识:文件操作,插入排序? 链表操作?
用STL中的list实现
*/
#include < iostream >
#include < fstream >
#include < list >
#include < string >
using namespace std;
void wordsort(ifstream & fin, list < string > & Q)
... {
string tmp;
char ch;
bool Inword; //判断是否在单词内
Inword = false;
tmp.clear();
while((ch = fin.get()) != EOF)
...{
switch(ch)
...{
case ' ':
case ',':
case '.':
Inword = false;
break;
default:
Inword = true;
break;
}
if(Inword == true)
...{
tmp += (ch >= 'A' && ch <= 'Z') ? ('a' + ch - 'A') : ch;
}
if(!tmp.empty() && !Inword)
...{
Q.push_back(tmp);
tmp.clear();
}
}
if(!tmp.empty())
Q.push_back(tmp);
Q.sort();
Q.unique();
}
int main()
... {
ifstream fin("a.txt");
list<string> Q;
wordsort(fin, Q);
fin.close();
for(list<string>::iterator p = Q.begin(); p != Q.end(); ++p)
cout << *p << ' ';
cout << endl;
return 0;
}
比如文件file.txt中存放的是单词
单词使用空格,逗号和点分隔,
若文件中是I don 't know you don 't know I know
则要输出
don 't
i
know
you
也就是需要对单词排序,没搞定这道垃圾题
考查知识:文件操作,插入排序? 链表操作?
用STL中的list实现
*/
#include < iostream >
#include < fstream >
#include < list >
#include < string >
using namespace std;
void wordsort(ifstream & fin, list < string > & Q)
... {
string tmp;
char ch;
bool Inword; //判断是否在单词内
Inword = false;
tmp.clear();
while((ch = fin.get()) != EOF)
...{
switch(ch)
...{
case ' ':
case ',':
case '.':
Inword = false;
break;
default:
Inword = true;
break;
}
if(Inword == true)
...{
tmp += (ch >= 'A' && ch <= 'Z') ? ('a' + ch - 'A') : ch;
}
if(!tmp.empty() && !Inword)
...{
Q.push_back(tmp);
tmp.clear();
}
}
if(!tmp.empty())
Q.push_back(tmp);
Q.sort();
Q.unique();
}
int main()
... {
ifstream fin("a.txt");
list<string> Q;
wordsort(fin, Q);
fin.close();
for(list<string>::iterator p = Q.begin(); p != Q.end(); ++p)
cout << *p << ' ';
cout << endl;
return 0;
}