Search code examples
c++formatted-input

C++ formatted input: how to 'skip' tokens?


Suppose I have an input file in this format:

VAL1 VAL2 VAL3
VAL1 VAL2 VAL3

I'm writing a program that would be interested only in VAL1 and VAL3. In C, if i wanted to 'skip' the second value, I'd do as follows:

char VAL1[LENGTH]; char VAL3[LENGTH];
FILE * input_file;
fscanf(input_file, "%s %*s %s", VAL1, VAL3);

Meaning, I'd use the "%*s" formatter to make fscanf() read this token and skip it. How do I do this with C++'s cin? Is there a similar command? Or do I have to read to a dummy variable?

Thanks in advance.


Solution

  • The C++ String Toolkit Library (StrTk) has the following solution to your problem:

    #include <string>
    #include <deque>
    #include "strtk.hpp"
    
    int main()
    {
       struct line_type
       {
          std::string val1;
          std::string val3;
       };
    
       std::deque<line_type> line_list;
    
       const std::string file_name = "data.txt";
    
       strtk::for_each_line(file_name,
                            [&line_list](const std::string& line)
                            {
                               strtk::ignore_token ignore;
                               line_type temp_line;
                               const bool result = strtk::parse(line,
                                                                " ",
                                                                temp_line.val1,
                                                                ignore,
                                                                temp_line.val3);
                               if (!result) return;
                               line_list.push_back(temp_line);
                            });
    
       return 0;
    }
    

    More examples can be found Here