如果我有这样的文件
1 5 6 9 7 1
2 5 4 3 8 9
3 4 3 2 1 6
4 1 3 6 5 4
我想对每一行中的数字进行排序.. 如何知道何时有换行符? 代码例如:
while (!input.eof) {
input>>num;
while (not new line ?){
input>>o;
b.push_back(o);
}
sort (b.begin(),b.end());
se=b.size();
output<<num<<" "<<b[se-1]<<endl;
b.clear();
}
注意:我试过 while(input>>num) 和 getline 现在可以和我一起工作 有什么想法吗?
最佳答案
您的输入无效!使用 stream.eof()
的循环测试作为输入的唯一控制总是错误的。您总是需要在尝试阅读之后测试您的输入。顺便说一句,我之前发布了如何保证对象之间没有换行符。已经有一个使用 std::getline()
作为第一阶段的答案,这有点无聊。这是另一种方法:
std::istream& noeol(std::istream& in) {
for (int c; (c = in.peek()) != std::char_traits<char>::eof()
&& std::isspace(c); in.get()) {
if (c == '\n') {
in.setstate(std::ios_base::failbit);
}
}
return in;
}
// ...
while (input >> num) {
do {
b.push_back(num);
} while (input >> noeol >> num);
std::sort (b.begin(),b.end());
se=b.size();
output<<num<<" "<<b[se-1]<<endl;
b.clear();
input.clear();
}
关于c++ - 虽然不是新线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21082537/