Question about std::getline and fstream::getline

Ok now, here's the question:

1
2
3
4
5
//if i use
std::getline(file, string);

//when i use
file.getline(mychars, 128)


Do i need to seekg?
No you don't.
I think i need to
this is actually my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
    srand(time(NULL));
    std::ifstream file;
    file.open("phrases.txt");
    int lines = 0;
    std::string none;
    while(std::getline(file, none))
    {
        lines++;
    }
    int number = rand() % lines+1;
    char phrase[256];
    file.clear();
    for(int i = 0; i < number;i++)
    {
        file.getline(phrase, 256);
    }
    return phrase;
}

and doesn't work as supposed.
1
2
3
4
    while(std::getline(file, none))
    {
        lines++;
    }
Are you just counting the lines or what are you trying to do? was dumb question.

Also, I believe you need to open the file again though you could try seekg. Since you just read in everything from the file then try to read in again an arbitrary number of lines to get to line x.
Last edited on
return phrase; - this looks like an error, since char phrase[256]; is a local variable which will go out of scope when the function terminates, thus trying to access it afterwards will not work.

It might be better to change the function to return a std::string instead.
If you're going to read everything in up to two times, I would just cache each line the first line through.

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
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>


std::string get_random_phrase()
{
    std::ifstream in("phrases.txt");

    std::vector<std::string> lines;
    std::string line;

    while (std::getline(in, line))
        lines.push_back(line); 
    
    return lines[std::rand() % lines.size()];
}

int main()
{
    std::srand(std::time(0));

    std::cout << get_random_phrase() << '\n';
}


Caching all of the lines in an object that persists the length of the program may be recommended if the function is called often.
Thank you a lot! That's seems a lot better! But i never used vectors.
Is there really that much difference between arrays other that methods?
Because modifing your code for an array seems simple...
The advantage of the vector is it can dynamically resize as required. if you tried to use a array, you'd be back where you were before with a need to first read the entire file in order to determine the array size, and allocate it with sufficient size, then you'd need to read it all again to populate the array. That adds more work.

In other respects, a vector can often be considered as a direct replacement for an array, it can be used with the same array[index] syntax which keeps things simple.

Topic archived. No new replies allowed.