get line from text file by line number

Nov 3, 2011 at 6:10pm
I have just finished a hangman game in win console with words selected randomly from an array of strings. I need to change it get words randomly. I do not wish to get all the words and put them in an array. Instead I want to go to a specific line (text file has 1 word per line) and put the word in a string. Is this complicated? Any help would be appreciated a lot.

Brandon
Nov 3, 2011 at 6:14pm
It seems to me what you are looking for is the seekg function.

http://www.cplusplus.com/reference/iostream/istream/seekg/

Or seekp for ostream.

http://www.cplusplus.com/reference/iostream/ostream/seekp/
Last edited on Nov 3, 2011 at 6:15pm
Nov 3, 2011 at 6:54pm
Could anyone write a small example pls? Say I need to get a word that is at line 3..
The links only seems to work with single characters. Is it the \n as a deliminator that has to do the magic?

thanks
Nov 3, 2011 at 6:58pm
1
2
3
4
5
6
7
ifstream f("input.txt");
string s;
getline(f, s);
getline(f, s);
getline(f, s); //here is 3rd line
processLine(s); //do what you want
f.close();


Is it you wanted?
Nov 3, 2011 at 7:19pm
Am I doing something wrong here? I am not getting anything..

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
#include <iostream>
#include <fstream>

#include <string>


using namespace std;


int main()

{

	ifstream f("input.txt");
	string s;
	getline(f, s);
	getline(f, s);
	getline(f, s); //here is 3rd line
	
	cout << s << endl;
	f.close();
	
	system("pause");
	
	return 0;


}
Nov 3, 2011 at 7:29pm
It is proper code.

Can you show content of "input.txt" file?

Is this file in your working folder? Isn't it empty?
Nov 3, 2011 at 7:36pm
Wonderful :) .. thanks a lot . It was in the wrong folder.

thanks again,
Nov 4, 2011 at 8:32am
Hi, its me again. I need the same procedure but with the difference to over write a specific line.
should I just use ofstream instead?
Nov 7, 2011 at 11:20pm
Yes, if you want to write then use ofstream. But you cannot modify text file.
So, my recommendation is: read the entire file in array of strings, modify them as needed and save to file in any order you want.
Topic archived. No new replies allowed.