1

if i have a file like

1 5 6 9 7 1 
2 5 4 3 8 9
3 4 3 2 1 6
4 1 3 6 5 4

and i want to sort the numbers in every line .. how to know when there is a newline ? code for example :

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

Note: i tried while(input>>num) and getline will now work with me any ideas ?

user2973413
  • 117
  • 1
  • 1
  • 9
  • 2
    If you want to read lines, your best bet is going to be `getline`. Note that [`while (!eof())` is wrong.](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – chris Jan 13 '14 at 01:22
  • Since it looks like you are iterating over every character individually, you might find it helpful to know that `"\n"` is the `CHAR` for a new line. – Alexander Jan 13 '14 at 01:23
  • Why eof is wrong? Std::getline itself does move the file towards the end – Gasim Jan 13 '14 at 01:25
  • 1
    @Gasim, click on the link that chris provided to see why `while (!eof())` is "wrong". More specifically, it's not a good way to check this kind of loop since one must attempt to read the EOF before `eof()` is true. It doesn't tell you if you are "at" the EOF. – lurker Jan 13 '14 at 01:26

2 Answers2

1

You can use std::getline together with std::istringstream to read the file line by line, and then process each line individually:

#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
} 

For further reference on how to read the file line by line, see this post.

ApproachingDarknessFish
  • 13,013
  • 6
  • 35
  • 73
Uli Köhler
  • 11,813
  • 14
  • 55
  • 105
1

Your input doesn't work! Using a loop testing for stream.eof() as the only control for the input is always wrong. You always need to test your input after you tried to read it. Incidentally, I posted earlier how you can guarantee that there is no newline between to objects. there is already an answer using std::getline() as a first stage which is somewhat boring. Here is an alternate approach:

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();
}
Dietmar Kühl
  • 141,209
  • 12
  • 196
  • 356