Reading lines from a text file

Hello.

I am trying to read lines from a .txt file like this:
1
2
3
// "file.txt"
This is the first line.
This is the second line.


To do this, I tried using the following code:
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
int main()
{
	std::ifstream data;
	data.open("file.txt");

	if (data.is_open())
	{
		std::string str, value;
		std::getline(data, str);
		std::stringstream sstream(str);

		while (std::getline(sstream, value))
		{
			if (value.length() > 0)
			{
				std::cout << str << std::endl;
			}
		}
	}

	else { /* ERROR */ }

	data.close();

        std::cin.get();
}


The output I want is:
1
2
This is the first line.
This is the second line.


However, all I am getting is:
1
2
This is the first line.
 


I can't quite see why this isn't working. I am decently familiar with file streams in C++, so I thought I would know what I was doing, but apparently not.

Any help would be appreciated.
I don't see the need for a stringstream there.
Simplify:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
    std::ifstream data("file.txt");

    if (data)
    {
        std::string str;

        while (std::getline(data, str))
        {
            if (str.length() )
                std::cout << str << std::endl;
        }
    }
    else 
    { 
        std::cout << "could not open file" << std::endl;
        return 1;
    }

    std::cin.get();
}


Or if you wanted to justify the use of a stringstream, here's an example:
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
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

int main()
{
    std::ifstream data("file.txt");
    if (!data)
    { 
        std::cout << "could not open file" << std::endl;
        return 1;
    }    
    
    std::string str;
    while (std::getline(data, str))
    {
        std::istringstream ss(str);
        std::string value;
        while (getline(ss, value, ' '))
            std::cout << value << std::endl;
        std::cout << std::string(40, '-') << std::endl;
    }
    
    std::cin.get();
}

This
is
the
first
line.
----------------------------------------
This
is
the
second
line.
----------------------------------------


Note: the original code executed line 9 once only:
 
    std::getline(data, str);
Last edited on
Topic archived. No new replies allowed.