【问题标题】:Splitting up lines into ints将行拆分为整数
【发布时间】:2009-12-18 02:17:26
【问题描述】:

我有一个从中读取的文件,它包含一堆行,每行都有不同数量的整数,我无法将其拆分为整数向量的向量。

这是我当前的代码。

std::vector<int> read_line()
{
    std::vector<int> ints;
    int extract_int;
    while((const char*)std::cin.peek() != "\n" && std::cin.peek() != -1)
    {
        std::cin >> extract_int;
        ints.push_back(extract_int);
    }
    return ints;
}
std::vector<std::vector<int> > read_lines()
{
    freopen("D:\\test.txt", "r", stdin);
    freopen("D:\\test2.txt", "w", stdout);
    std::vector<std::vector<int> > lines;
    while(!std::cin.eof())
    {
        lines.push_back(read_line());
    }
    return lines;
}

问题是所有整数都被读取为一行。

我做错了什么?

【问题讨论】:

    标签: c++ input stdin std


    【解决方案1】:

    您可能希望使用getline() 读取一行,然后在该行之外使用string stream,而不是尝试将整个文件视为单个流。

    【讨论】:

    • 这样做有什么好处?
    【解决方案2】:

    问题在于您的(const char *)std::cin.peek() != "\n" 演员表。 casts are evil;尽量避免使用它们。以下代码有效:

    std::vector<int> read_line()
    {
        std::vector<int> ints;
        int extract_int;
        while(std::cin.peek() != '\n' && std::cin.peek() != -1)
        {
            std::cin >> extract_int;
            ints.push_back(extract_int);
        }
    
        std::cin.ignore(); // You need this to discard the \n
    
        return ints;
    }
    

    【讨论】:

    • 在这种情况下,与其说是演员阵容是邪恶的,不如说是试图将 const char* 与 == 进行比较。
    • +1 给 Dan 以正确识别根本原因。原始代码实际上是检查两个字符串的指针是否相等,人们希望它们不相等。
    【解决方案3】:

    将单行读入向量

    std::vector<int> read_line()
    {
      std::vector<int> ints;
    
      std::string line;
      std::getline(std::cin, line);
    
      int i;
      std::stringstream ss(line);
      while (ss >> i)
        ints.push_back(i);
    
      return ints;
    }
    

    然后是所有的向量

    std::vector< std::vector<int> > read_lines()
    {
      std::vector< std::vector<int> > lines;
    
      while (std::cin) {
        std::vector<int> line = read_line();
    
        if (std::cin)
          lines.push_back(line);
      }
    
      return lines;
    }
    

    然后用

    打印结果
    template<class T>
    struct print : public std::unary_function<T,void>
    {
      print(std::ostream &out) : os(out) {}
      void operator() (T x) { os << '[' << x << ']'; }
      std::ostream &os;
    };
    
    void print_vector(const std::vector<int> &v)
    {
      std::for_each(v.begin(), v.end(), print<int>(std::cout));
      std::cout << '\n';
    }
    
    int main()
    {
      std::vector< std::vector<int> > lines = read_lines();
    
      std::for_each(lines.begin(), lines.end(), print_vector);
    
      return 0;
    }
    

    例如:

    $猫输入 1 2 3 4 5 6 7 8 9 10 $ ./try.exe

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 2016-11-28
      • 2018-01-06
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 2013-03-21
      • 2015-12-19
      相关资源
      最近更新 更多