Read and parse line in C/C++; put tokens in an array or vector or similar structure
I have to submit code to one of the problems in ACM IPC and, as you may know, the time counts a lot. So, I have to 开发者_StackOverflowread efficiently an input like this: The first line will contain the sequence of integer values associated and the second line will contain the sequence of integer values associated with another sequence. E.g.:
3 2 1 4 5 7 6
3 1 2 5 6 7 4
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
255
255
I have to put the 1st line in an array and the second in another and pass both in a function.
How do I read and put these in C/C++? I was thinking in a C way, but my approach would have 2 while's... I have preference reading with scanf, but the parsing can be done as you want.
Please , help this newb!
Read the lines using std::getline()
. Then use a std::stringstream
to parse each line. As this is for a competition, you won't be wanting actual code.
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
typedef std::vector< int > ints_t;
void dump_ints( const ints_t& input )
{
std::copy(
input.begin(),
input.end(),
std::ostream_iterator< int >( std::cout, " " ) );
std::cout << std::endl;
}
void foo( const ints_t& first, const ints_t& second )
{
dump_ints( first );
dump_ints( second );
}
bool parse_line( std::istream& is, ints_t* output )
{
std::string line;
if ( std::getline( is, line ) )
{
std::istringstream raw_ints( line );
std::copy(
std::istream_iterator< int >( raw_ints ),
std::istream_iterator< int >(),
std::back_inserter( *output ) );
return true;
}
else
{
return false;
}
}
bool parse( std::istream& is, ints_t* first, ints_t* second )
{
const bool result = parse_line( is, first ) && parse_line( is, second );
return result;
}
void run( std::istream& is )
{
while ( is )
{
ints_t first;
ints_t second;
if ( parse( is, &first, &second ) )
{
foo( first, second );
}
}
}
int main()
{
//if you want to read input from file use ifstream and comment istringstream
// std::ifstream is( "put_here_a_path_to_input_file" );
std::istringstream is(
"3 2 1 4 5 7 6\n"
"3 1 2 5 6 7 4\n"
"7 8 11 3 5 16 12 18\n"
"8 3 11 7 16 18 12 5\n"
"255\n"
"255\n"
);
run( is );
}
You could also use strtok() and strdup().
See example of using strtok() and strdup(). strtok() would then be used to extract the individual tokens - strdup() to allocate space an copy them.
精彩评论