Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I skip reading a line in a file in C++?

Tags:

c++

file-io

The file contains the following data:

#10000000    AAA 22.145  21.676  21.588
10  TTT 22.145  21.676  21.588
1  ACC 22.145  21.676  21.588

I tried to skip lines starting with "#" using the following code:

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

using namespace std;
int main() {
     while( getline("myfile.txt", qlline)) {

           stringstream sq(qlline);
           int tableEntry;

           sq >> tableEntry;

          if (tableEntry.find("#") != tableEntry.npos) {
              continue;
          }

          int data = tableEntry;
   }
}

But for some reason it gives this error:

Mycode.cc:13: error: request for member 'find' in 'tableEntry', which is of non-class type 'int'

like image 239
neversaint Avatar asked Feb 23 '09 06:02

neversaint


People also ask

How do I skip a line in C?

In most C compilers, including ours, the newline escape sequence '\n' yields an ASCII line feed character. The C escape sequence for a carriage return is '\r'.

How do you skip to the next line in fscanf?

I was able to skip lines with scanf with the following instruction: fscanf(config_file, "%*[^\n]\n");

How do you skip a line in C ++?

The other way to break a line in C++ is to use the newline character — that ' \n ' mentioned earlier. This is line one. This is line two. This is line one.


2 Answers

Is this more like what you want?

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

int main() 
{
    fstream fin("myfile.txt");
    string line;
    while(getline(fin, line)) 
    {
        //the following line trims white space from the beginning of the string
        line.erase(line.begin(), find_if(line.begin(), line.end(), not1(ptr_fun<int, int>(isspace)))); 

        if(line[0] == '#') continue;

        int data;
        stringstream(line) >> data;

        cout << "Data: " << data  << endl;
    }
    return 0;
}
like image 102
CTT Avatar answered Oct 19 '22 13:10

CTT


You try to extract an integer from the line, and then try to find a "#" in the integer. This doesn't make sense, and the compiler complains that there is no find method for integers.

You probably should check the "#" directly on the read line at the beginning of the loop. Besides that you need to declare qlline and actually open the file somewhere and not just pass a string with it's name to getline. Basically like this:

ifstream myfile("myfile.txt");
string qlline;
while (getline(myfile, qlline)) {
  if (qlline.find("#") == 0) {
    continue;
  }
  ...
}
like image 45
sth Avatar answered Oct 19 '22 15:10

sth