Detecting the end of line in a text file

Pages: 12
closed account (21R4z8AR)
yoo im soo confused! Now that code I made that was working doesnt even work! :((((
I literally changed nothing. I don't understand. :(

Everything worked when I first made it but now when I enter a text file with
1

2 2

2 2 x

2 3 x y


The program outputs
a.txt

a value only
Error no more data
Last edited on
If the file is exactly as you've shown then it has blank lines in it, and you (inexplicably) told your program to break the input loop if it encounters a blank line ("error no more data"). Just have it say "blank line" (or nothing) and continue (you don't really need all the continues, though).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    string filename;
    getline(cin, filename);
    ifstream inputFile(filename);
    string line;
    while (getline(inputFile, line)) {
        int a = 0, b = 0;
        string c = "c", d = "d";
        istringstream sin(line);
        if (!(sin >> a)) {
            if (sin.eof())
                cerr << "blank line\n";
            else
                cerr << "incorrect datatype\n";
        }
        else if (!(sin >> b)) {
            if (sin.eof())
                cerr << "a value only\n";
            else
                cerr << "incorrect data type\n";
        }
        else if (!(sin >> c))
            cerr << "a and b value only\n";
        else if (c != "x" && c != "y")
            cerr << "c value isnt correct\n";
        else if (!(sin >> d))
            cerr << "a and b and c value only\n";
        else if (d != "x" && d != "y")
            cerr << "d value isnt correct\n";
        else if (!(sin >> ws).eof())
            cerr << "ignorning extra data\n";
    }
}

Last edited on
closed account (21R4z8AR)
Is there any function that can remove the spaces in my text file :/ its for an assignment and the text files supplied have a space in between. It said feel free to use any functions that might help such as "using peek() function to remove any tabs or spaces; etc.)." in the assignment details
Last edited on
I assume by "spaces" you mean blank lines. The above code skips them just fine. All you need to do is stop it from printing "blank line". It'll just do nothing and loop around for the next line. Something like this:

1
2
3
4
5
        if (!(sin >> a)) {
            if (!sin.eof())
                cerr << "incorrect datatype\n";
            // otherwise it's a blank line; ignore it
        }

closed account (21R4z8AR)
hm thats weird, my program seems to think every blank line is an eof :/
I feel like I'm talking to myself....
closed account (21R4z8AR)
oh im sorry i understand now
Excellent!
Topic archived. No new replies allowed.
Pages: 12