Why is ifstream.getline() cutting short?

I have a program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>

using namespace std;

void main(){
    char str[80];
    ifstream in("C:\\somefile.txt")

    in.getline(str, 25);
    cout << str << endl;
    in.getline(str, 25);
    cout << str << endl;

    in.close();
    cin.ignore();
    return;
}


When you run it, it should show you the text in the first two lines of the file. If either line has more than 24 characters, then it cuts that line off at 24 characters.

That's what I expected. What I didn't expect is that, if the first line gets cut off, the second line displays nothing at all. Why is this?
Last edited on
Turns out that if I add in.clear(); between the commands, then the second line finishes up by displaying what the first didn't have room for. No part of the second line of the file is displayed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>

using namespace std;

void main(){
    char str[80];
    ifstream in("C:\\somefile.txt")

    in.getline(str, 25);
    cout << str << endl;

    in.clear();   //Added to this version.

    in.getline(str, 25);
    cout << str << endl;

    in.close();
    cin.ignore();
    return;
}
Last edited on
Check this out. Enter "asdf" hit enter, then enter "1234" and hit enter again. Then run it again and enter "asdf1234" in one line and hit enter. The thing is that when getline(str,n) extracts n characters (including '\0') the failbit is set. Clearing the stream's status will work, but mind that the stream's buffer is as you left it...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    char str[80];

    cin.getline(str,5);
    cout << str << endl;

    cout << (bool)cin << endl;

    cin.clear();

    cin.getline(str,5);
    cout << str << endl;

    cout << (bool)cin << endl;

    system("pause");
    return 0;
}

http://cplusplus.com/reference/iostream/istream/getline/

EDIT: Ah, I see you figured it out yourself :)
Last edited on
Also check this out:

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
#include <iostream>
#include <string>
using namespace std;

const int SIZE=4;

int main()
{
    string input;
    string line;
    
    cout << "enter a line up to "
        << SIZE << " chars long" << endl;

    getline(cin,input);
    line=input.substr(0,SIZE);

    cout << "you entered: " << line << endl;

    cout << "enter another line up to "
        << SIZE << " chars long" << endl;

    getline(cin,input);
    line=input.substr(0,SIZE);

    cout << "you entered: " << line << endl;

    cout << "hit enter to quit...";
    cin.get();
    return 0;
}
Topic archived. No new replies allowed.