0
1 = 0 0 97 218
2 = 588 0 97 218
3 = 196 438 97 218
4 = 0 657 97 218
5 = 294 438 97 218

我有像上面这样的 txt 文件。如何在没有 = 的情况下从这个文件中只读取整数?

4

2 回答 2

1

另一种可能性是分类=为空白的方面:

class my_ctype : public std::ctype<char>
{
    mask my_table[table_size];
public:
    my_ctype(size_t refs = 0)  
        : std::ctype<char>(&my_table[0], false, refs)
    {
        std::copy_n(classic_table(), table_size, my_table);
        my_table['='] = (mask)space;
    }
};

然后用包含此方面的语言环境为您的流灌输,然后读取数字,就好像=根本不存在一样:

int main() {
    std::istringstream input(
            "1 = 0 0 97 218\n"
            "2 = 588 0 97 218\n"
            "3 = 196 438 97 218\n"
            "4 = 0 657 97 218\n"
            "5 = 294 438 97 218\n"
        );

    std::locale x(std::locale::classic(), new my_ctype);
    input.imbue(x);

    std::vector<int> numbers((std::istream_iterator<int>(input)),
        std::istream_iterator<int>());

    std::cout << "the numbers add up to: " 
              << std::accumulate(numbers.begin(), numbers.end(), 0) 
              << "\n";
    return 0;
}

诚然,将所有数字相加可能不是很明智,因为每行的第一个数字似乎是一个行号——这只是一个快速演示,以表明我们确实在读取数字而没有额外的“东西”造成任何问题。

于 2012-05-18T03:22:50.647 回答
0

这是基本框架:逐行阅读并解析。

for (std::string line; std::getline(std::cin, line); )
{
     std::istringstream iss(line);
     int n;
     char c;

     if (!(iss >> n >> c) || c != '=')
     {
         // parsing error, skipping line
         continue;
     }

     for (int i; iss >> i; )
     {
         std::cout << n << " = " << i << std::endl; // or whatever;
     }
}

要通过 读取文件std::cin,请将其通过管道传输到您的程序中,例如./myprog < thefile.txt.

于 2012-05-17T21:36:00.957 回答