go to new line

Hello! I have a text file "try.txt", which has 10 lines:

Chun Mee	Pu-eth	Slightly sweet and earthy	
Wuyi	Green	Strong and smooth	
Genmai	Mixed with flowers	With distinct oaky notes	
Maitre	Mixed with herbals	Fresh, strong and malty	
Osmanthus	White	Sweet, smoky and malty	
Kenilworth	Red	Strong, malty and smooth	
Masala	Spice mix	Fresh, strong and malty	
Manluo King	Herbal	strong	
Vithanaka	Black	Astringent and strong		
Ali Uva	With fruits	Sweet and smoky	


I`d like to get words before '\t' from lines, whose number = iter_mum, but always I get words only from 4 first lines. Here is the 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <fstream>
#include <string.h>
#include <cstdlib>
#include <fstream>
#include <limits>

using namespace std;

fstream& go_line(fstream& file, unsigned int num){
	for(int i=0; i < num - 1; ++i){
		file.ignore(numeric_limits<streamsize>::max(),'\n');
	}
	return file;
}

void func(int iter_num){
	fstream usr_file;
	usr_file.open("try.txt");
	char str_key[10];
	int t = 1;

	while(t<iter_num+1){
	go_line(usr_file, t);
	usr_file.getline(str_key, sizeof(str_key), '\t');
	cout<<"STR "<<str_key<<endl;
	t++;
	}

}//func

int main(){
	cout<<"10 iter: "<<endl;
	func(10);
	cout<<"9 iter: "<<endl;
	func(9);
	cout<<"8 iter: "<<endl;
	func(8);

	return 0;
}


Here is what I get:


10 iter: 
STR Chun Mee
STR Wuyi
STR Maitre
STR Masala
STR 
STR 
STR 
STR 
STR 
STR 

9 iter: 
STR Chun Mee
STR Wuyi
STR Maitre
STR Masala
STR 
STR 
STR 
STR 
STR 

8 iter: 
STR Chun Mee
STR Wuyi
STR Maitre
STR Masala
STR 
STR 
STR 
STR 


Have no ideas how to solve this problem.
Last edited on
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
30
31
32
33
34
#include <iostream>
#include <fstream>
#include <string>
#include <limits>

std::istream& goto_line( std::istream& file, unsigned int num ){

    file.clear() ; // *** clear failed/eof state (if any)
    file.seekg(0) ; // *** seek to the beginning

    for( unsigned int i = 1; i < num ; ++i )	{
        file.ignore( std::numeric_limits<std::streamsize>::max(),'\n' );
	}

	return file;
}

std::istream& get_line( std::istream& stm, std::string& line, unsigned int n ) {

    goto_line( stm, n ) ;
    return std::getline( stm, line ) ;
}

int main() {

    std::ifstream file(__FILE__) ;

    for( unsigned int n : { 4, 6, 200, 1, 4, 34, 35, 12, 6, 28 } ) {

        std::string line ;
        if( get_line( file, line, n ) ) std::cout << n << ". " << line << '\n' ;
        else std::cout << "*** error: there is no line# " << n << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/e68b3ffc33334eeb
Thanks a lot! It works now!
Topic archived. No new replies allowed.