Reading lines in file

Hello,

I'm running a program that reads lines from files. The program gets the total length of the file using the push_back container.
however, I'm trying to read the particular lines of a file.

If a line beginning with some character is encountered, I want to get the line number that that character was found.

I'm not sure how to go about it.

Please help!
pseudocode
file = open ...
line_counter = 0
while there are things to read
   str = getline(file)
   line_counter ++;
   if some_function(str[0]) == true 
   then cout << "found " << str << " on line " << line_counter << ", starting with " << str[0] << '\n';
Which part of that is not clear?
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
line_counter = 0;
 while(getline(myfile,line)){
         line_counter++;
          printf("%s\n", line); 
          lines.push_back(line);
          printf("%i", lines.size());
          istringstream isline(line);
          if (isline>>ch)
          {  
            switch (ch)
            {
                case 'A':
                {
                    int input;
                    isline>>input;
                    cout<<line_counter<<'\n';
                   
                }
                break;
                case 'B':
                {
                    int input;
                    isline>>input;
                    cout<<line_counter<<'\n';
                   
                }
                break;


The above is a snippet of my code. I have various switch statements for which I need to read the line. I'm still not getting the line number. Please help me.
Last edited on
What are you getting then?

printf only works when the string is a char*, while you have an std::string. You could use line.c_str(), but there is no point in mixing c and c++ io libraries at all. It's ugly. Just do cout << line;
I think we have to read every line .. but we print the line number and that particular line .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
FilePtr file = open ...
int line_counter = 0
cout<<"Enter the particular string like 'Something' that you want to search in the file  "
cin>>findstr ; 
while( !file.eof())
{
   if(getline(file).find(findstr))
	{
		cout<<"\n String present in the line "<<	line_counter ++;
		cout <<"\n "<<file;

	}
   if some_function(str[0]) == true 
   then cout << "found " << str << " on line " << line_counter << ", starting with " << str[0] << '\n';
}


please let me know if i am wrong .
hamsterman's method actually works. some variables in my program were throwing it off. Thanks for your help.
Topic archived. No new replies allowed.