Search code examples
cinputgetline

Is it possible to getLine() in C starting at given index?


The getline function scans the whole input line and stores it in a given char array. Assume I want to use the getline method to scan the input starting at a given index. How can I achieve this?

For example, let's say the input is: Hello, my name is John.

I want getline to store only my name is John.

    char* cmd = NULL;
    size_t size = 0;

    getline(&cmd, &size, stdin); // code to get whole input line.

Thank you


Solution

  • getline has no such capability. However, it reads from the default input stream and there are many other functions that read from that stream too.

    One of the most basic reading function is getc(). It reads one single character. So, to "make" the getline start reading from Nth character, use N times getc just before it.

    // "skip" N characters - read N and forget them immediatelly
    for(int i=0;i<N;++i)
        getc(); // remember: that's a READ, it can FAIL
    
    getline( ... ); // remember: that's a READ, it can FAIL
    

    Of course, that way, all those skipped characters are unrecoverable now (well, almost, but let's skip it). Also, this method does not allow you to "move backwards". You can only skip "forwards".

    If you ever need to look back at any characters in the input stream, you need some kind of buffering. Read all or a part of the input into the buffer, look at the buffer as a whole (array of data, etc), cut the interesting parts out of the buffer, load new/next data into buffer, and so on. Buffers are good! :)

    However, this read-one-by-one is OK sometimes too. The main plus of this way of "skipping" is that it does not use any extra memory at all. If your data-to-be-skipped is large like several kilo/mega/../bytes then it's really wasteful to pack all it into a buffer just to throw it out immediatelly.