Getline problems

Hi, I need some help with the ifstream and the associate getline function.

I'm trying to read some text (on multiple lines) from a simple text file.

1
2
3
4
5
6
7
8
9
10
11
12
13

std::ifstream inputFile;
    inputFile.open("dchp.conf");
    char* buffer = new char[80];
    inputFile.getline(buffer, sizeof(buffer), '\n');
    std::cout << buffer << std::endl;
    for(int i = 0; i < 80; i++){
        std::cout << buffer[i];
    }
    std::cout << std::endl;
    delete buffer;
    *buffer = NULL;


When I'm trying to display buffer with cout << buffer; nothing is displayed.
And when I'm trying to display it char by char it only show me some weird characters.

Also, I was wondering if it mattered that the file is actually a ".conf" instead of a ".txt". Here is the content of the ".conf":

30
255.255.255.0
192.168.1.1
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
192.168.1.10
using sizeof(buffer) in the getline call looks suspicious to me. You want the size of the array, not the size of the pointer variable. I'm not sure that sizeof(buffer) will return 80 but will return 4 instead. The file extension makes no difference.

Moreover, I do not see any attempt to validate that the file was opened. Was it? Perhaps the getline call is not reading anything and you are left with an uninitialized buffer. You should consider using std::fill to fill the array with zeros or simply use a std::vector for your array. At least then you won't be printing garbage. Also, the for loop is going to print 80 characters regardless of what was read so of course you are going to see a lot of garbage since the array was never initialized in the first place. Even if the file was opened only a few characters are being read and the rest of the buffer is uninitialized.

1
2
3
4
5
#include <vector>

int BUFFER_SIZE(80);
std::vector<char> buffer(BUFFER_SIZE); // zero initialized automatically
inputFile.getline(&buffer[0], BUFFER_SIZE); // '\n' is the default delimiter 
Last edited on
An even better way is to use std::string and its getline method.
http://cplusplus.com/reference/string/getline/
Thanks a lot, it's now working fine !!

By the way, thanks for reminding me of checking for my file to open correctly.

NEV
Topic archived. No new replies allowed.