Fstream Question

Alright, so I am a little rusty with fstream and need a little assistance.

I am trying to write a while loop that will count the number of elements/characters of a single line of a file (called spcfile). What I have right now currently counts the total number of characters of the ENTIRE file, but I just want the characters for only a single line.

Is this possible?

Here's the loop:

1
2
3
4
5
6
7
8
9
        spcfile.get(c);
        while (spcfile) {
            while (spcfile && c != '\n') {
                numchars = numchars + 1;
                spcfile.get(c);
            }
            numlines = numlines + 1;
            spcfile.get(c);
        }
Last edited on
You are continuing to increment numchars after you've hit a newline (i.e., when you loop back to line 2 because you've reached a newline, numchars is still the value of the number of chars in that previous line and continues counting from there). You could store those values into an array or something as you get them then reset the counter to 0.
I should probably also note that each line has a fixed size of 256 characters, I'm actually really trying to read in the size of the line and number of lines. The program is actually blind to these sizes which is why it needs to read it in first (this is a default constructor for a class).
Last edited on
@Merriak:
I should probably also note that each line has a fixed size of 256 characters


i'm afraid you got this wrong, the length of a line:
1- visually, depends on the text editor you're using to explore the file.
2- actually, a line doesn't have a specific length, it's all the characters between two newline characters (maybe "line feed, carriage return" pair).

if you want CMD environment, it really have a fixed max line length (80 characters) that can be changed from the properties of CMD, just google:
change CMD width.
You can do this two ways:

1- Useing getline, the obvious choice.

2- Useing .get() until you hit a '\n' character (newline character, which is what getline does by default)

The first method involvs a string:

1
2
3
4
5
6
7
string myline = "";
ifstream in;
in.open(file.c_str(), ios::in);
getline(in, myline);
in.close();
cout<< "The number of elements is "<< myline.size()<< endl;
//this is fairly simple, using pre-existing algorithms. 


second method:

1
2
3
4
5
6
7
8
//this is basically going to be getline's emplementation
while(in.good())
{
    //you will need an integer to count
    in.get(ch);
    //you figure out how to stop it
    //hint: use a bool
}


While using .get() is nice, I wouldn't use it unless I wanted to move data from one file to another.

I would also like to add:
If my professor wanted me to use .get() real bad, I would just write the emplementation of getline...
Last edited on
Topic archived. No new replies allowed.