我不能在调用istream作为参数的函数中使用ifstream吗?

时间:2014-09-11 18:23:21

标签: c++ ifstream

这是编程原理和使用C ++实践中第10章的练习。 该计划使用点:

  1. 它提示用户输入(x,y)对。然后将它们存储在名为original_points的点矢量中。
  2. 将原始点打印到文件
  3. 程序然后读取文件以检索相同的点,存储在名为processed_points
  4. 的点矢量中
  5. 比较两个向量,如果它们不相同,则程序抛出错误。
  6. 问题是processed_points的{​​{1}}为0,只有在我使用size()获取这些点时才会发生这种情况。这个功能出了什么问题?

    get_vector_points()

    请注意,我使用自定义Point。完整代码位于http://pastebin.com/ZvfcZxf3

    对编码风格/可读性的任何评论都表示赞赏。

3 个答案:

答案 0 :(得分:4)

电话

read_from_file(path,original_points);

正在读取向量original_points,而不是processed_points

答案 1 :(得分:2)

您应尝试以不同的方式阅读文件:

void get_vector_points(istream& ist, vector<Point>& points)
{
   std::string line;
   std::string first, second;
   while(std::getline(ist,line)) 
   // this should get every line in the file as a string.
   // if the formatting of the file is 2 doubles per line.
   // You will need to do the parsing yourself by grabbing each value
   {
   // example first line:    123   321
    first = line.split[0]; // this is not a real function this is just Psudo code
    //first = "123"
    second = line.split[1];// for parsing text and splitting into 2 doubles
    // second = "321"
    Point p;
    p.x = atoi(first); // atoi is = ascii to int.  Makes a string intager into a 
    p.y = atoi(second);// actual int data type
    // p.x = 123   p.y = 321
    points.push_back(p)
    else return;
   }
}

答案 2 :(得分:1)

此外,您的函数get_vector_points会将输入流置于失败状态。您可以检查EOF并读取分隔符(空格)以避免它。

这里有整数:

#include <iostream>
#include <sstream>
#include <vector>

std::istream& get_integers(std::istream& stream, std::vector<int>& integers)
{
    int n;
    // Read integers and trailing white spaces.
    while( ! stream.eof() && stream >> n) {
        integers.push_back(n);
        stream >> std::ws;
    }
    return stream;
}

int main()
{
    std::istringstream input(" 1 2 3 ");
    std::vector<int> integers;
    // Read and test the result:
    if( ! get_integers(input, integers)) std::cout << "Failure\n";
    else {
        for(int i : integers)
            std::cout << i;
        std::cout << '\n';
    }
}
相关问题