7

データが次のように見える不規則なリストがあります。

[Number] [Number]
[Number] [Number] [Number] 
[Number] [Number] [Number] 
[Number] [Number] [Number] 
[Number] [Number] [Number] 
[...]

Notice that some lines have 2 numbers, some have 3 numbers. Currently I have my input code look like these

inputFile >> a >> b >> c;

However, I want to it ignore lines with only 2 numbers, is there a simple work around for this? (preferably without using string manipulations and conversions)

Thanks

4

3 に答える 3

13

getline を使用してから、各行を個別に解析します。

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::string   line;
    while(std::getline(std::cin, line))
    {
        std::stringstream linestream(line);
        int a;
        int b;
        int c;
        if (linestream >> a >> b >> c)
        {
            // Three values have been read from the line
        }
    }
}
于 2011-07-27T19:43:49.243 に答える
4

私が考えることができる最も簡単な解決策は、 を使用してファイルを 1 行ずつ読み取り、各行std::getlineを に順番に保存してstd::istringstreamから、それを実行>> a >> b >> cして戻り値を確認することです。

于 2011-07-27T19:41:31.193 に答える
2
std::string line;
while(std::getline(inputFile, line))
{
      std::stringstream ss(line);
      if ( ss >> a >> b >> c)
      {
           // line has three numbers. Work with this!
      }
      else
      {
           // line does not have three numbers. Ignore this case!
      }
}
于 2011-07-27T19:44:47.793 に答える