1

我必须向 ACM IPC 中的一个问题提交代码,而且您可能知道,时间非常重要。所以,我必须有效地读取这样的输入:第一行将包含相关的整数值序列,第二行将包含与另一个序列相关的整数值序列。例如:

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

我必须将第一行放入一个数组中,将第二行放入另一个数组中,并将两者都传递给一个函数。

我如何阅读这些内容并将其放入 C/C++ 中?我以 C 的方式思考,但我的方法将有 2 段时间......我喜欢使用 scanf 阅读,但可以根据需要进行解析。

请帮助这个新手!

4

3 回答 3

3

使用 阅读这些行std::getline()。然后使用 astd::stringstream来解析每一行。因为这是为了比赛,所以你不需要实际的代码。

于 2010-02-17T14:33:14.837 回答
1
#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 );
}
于 2010-02-17T14:56:22.933 回答
0

您还可以使用 strtok() 和 strdup()。

请参阅使用 strtok()strdup()的示例。然后 strtok() 将用于提取各个标记 - strdup() 分配空间并复制它们。

于 2010-02-17T14:48:55.367 回答