tryin to learn how to work with txt files..

i have two questions:
1) why does the line cout<<line<<endl; in the end of the file doesnt print anything on the screen?
2)lets say i want the string line to hold only, for example, the second word in the file, how can i do that??
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
using namespace std;

int main()
{
	string line;
	ifstream myfile ("example.txt");
	if (myfile.is_open())
	{
		while (! myfile.eof())
		{
	             getline (myfile,line);
                     myfile.close();
		}
	}
	else
		cout<<"Unable to open the file."<<endl;

	cout<<line<<endl;

	return 0;
}
Last edited on
What are the contents of "example.txt"?
let say for example the contents is " word1 word2, word3"
If those words would have been seperated in "paragraphs" like
"word1
word2
word3"
you could use something like while (getline(myfile, firstword) && getline(myfile, secondword))
You can probably get by just using formatted input that skips whitespace automatically. Something like this:
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 <fstream>
#include <string>
using namespace std;

int main()
{
    string line;
    ifstream myfile ("example.txt");
    int n = 0;
    if(!myfile)
    {
        cout<<"Unable to open the file."<<endl;
        return 1;
    }
    
    while(myfile >> line)
    {
        cout << "Word " << ++n << ": " << line << endl;
    }

    return 0;
}


I used the example you gave for "example.txt":
 word1 word2, word3


This is the output I saw:
Word 1: word1
Word 2: word2,
Word 3: word3
Last edited on
1) why does the line cout<<line<<endl; in the end of the file doesnt print anything on the screen?

Because the original code reads the first line then immediately closes the file. Then the loop is executed a second time (which doesn't make much sense, as the file is now closed), but line is set to an empty string, and both the fail() and eof() flags are set for the file, thus terminating the loop.

If you wanted to output the second line from the file (which I know wasn't exactly what you asked), you might do something like this:
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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream myfile ("input.txt");
    if (!myfile.is_open())
    {
        cout<<"Unable to open the file."<<endl;
        return 1;
    }
    
    string line;
    int count = 0;

    while (getline(myfile,line))
    {
        count++;
        if (count == 2)
            break;
    }

    cout << line << endl;

    return 0;
}

If you wanted the second word rather than second line, replace
while (getline(myfile,line))
with
while (myfile >> line)
Topic archived. No new replies allowed.