2014-01-13 48 views
1

,如果我有一个像虽然不是新的生产线

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(); 
} 

注:我试图在(输入>> NUM)和函数getline现在将我 任何工作思路?

+0

什么是“输入”? –

+2

如果你想读线条,你最好的选择就是getline。请注意['while(!eof())'是错误的。](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – chris

+0

因为它看起来你正在逐个遍历每一个字符,你可能会发现''\ n“'是新行的'CHAR'是有帮助的。 – Alexander

回答

1

可以一起使用std::getlinestd::istringstream到逐行读取文件中的行,然后单独处理的每一行:

#include <sstream> 
std::string line; 
while (std::getline(infile, line)) 
{ 
    std::istringstream iss(line); 
    int a, b; 
    //You can now read the numbers in the current line from iss 
} 

有关如何逐行读取文件中的行进一步参考,见this post

1

您的输入无法使用!使用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(); 
}