Copy only select elements of a vector to another

I have a data file such as:

(* Sunspot data collected by Robin McQuinn from *)
(* http://sidc.oma.be/html/sunspot.html         *)

(* Month: 1749 01 *) 58
(* Month: 1749 02 *) 63
(* Month: 1749 03 *) 70
(* Month: 1749 04 *) 56


My code is:

1
2
3
4
5
6
7
8
9
10
11
 ifstream infile{filename};
istream_iterator<char> infile_begin{ infile };
istream_iterator<char> eof{};
vector<char> file{ infile_begin, eof };
  
//remove comments then copy

vector<int>NoComm; //declare new vector
NoComm = file //copy

//then print out vector later on 

My desired output:

58
63
70 
56


My issues is how do I remove the comments, so everything between (* and *) then copy it over to my second vector?


Last edited on
1) Iterate over each element of your file vector
2) Parse the string to extract only the integer - you know the symbols that indicate the start and end of the bits you don't want, so it should be easy then the find the bit you do want.
3) Store that integer in the NoComm vector

You may be able to do something fancy with boost transform iterators, if you want to be all fancy and modern, but that's the old-school way of doing it :)
Using std::regex (note: does not account for comments nested within comments):

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
42
43
44
#include <iostream>
#include <string>
#include <regex>
#include <sstream>
#include <vector>

std::string strip_comments( std::string str )
{
    // \(\* - literal '(' immediately followed by literal '*'
    // .*? - zero or more repetitions of any character, match as few as possible
    // *\) - literal '*' immediately followed by literal ')'
    static const std::regex comment_re( R"(\(\*.*?\*\))" ) ;
    return std::regex_replace( str, comment_re, "" ) ;
}

std::vector<int> get_numbers( std::istream& stm  )
{
    std::vector<int> result ;

    std::string line ;
    while( std::getline( stm, line ) )
    {
       try { result.push_back( std::stoi( strip_comments(line) ) ) ; }
       catch( const std::exception& ) { /* ignore lines that don't contain a number*/ }
    }

    return result ;
}

int main()
{
     std::istringstream file(
                              "(* Sunspot data collected by Robin McQuinn from *)\n"
                              "(* http://sidc.oma.be/html/sunspot.html         *)\n"
                              "(* Month: 1749 01 *) 58\n"
                              "(* Month: 1749 02 *) (* another comment *) 63\n"
                              "(* Month: 1749 03 *) 70 (* a trailing comment *)\n"
                              "(* Month: 1749 04 *) 56\n"
                            ) ;

    const std::vector<int> numbers = get_numbers(file) ;

    for( int value : numbers ) std::cout << value << '\n' ;
}

http://rextester.com/BZQAMO98567
Topic archived. No new replies allowed.