C ++遇到Fstream问题并将数据存储到数组中

时间:2017-02-06 15:53:18

标签: c++ arrays fstream

对于我正在处理的作业,我想要流式传输文件并找到两点之间的距离。在ifile中,每行有6个整数。由于每个pointdistance有3个点,我决定制作2个大小为3的数组。但是,我很难将数据输入数组。以下是ifile的样子。

 2     5     2     8     5     2
 9     0     0     1     3     0
 0     8     8     9     6     3
 3     9     1     8     5     2
 1     4    10     0     0     9
 9     8     1     3     6     8
 9    10     7     3     2     5

以下是我一直在处理的代码示例。

#include <cmath>
#include <fstream>
#include <string>
#include <iostream>


using std::cout; 
using std::endl; 
using std::sqrt; 
using std::ifstream; 
using std::string; 


namespace roz
{
bool readpoints(ifstream&ifile, int p1[], int p2[], int sz);
static int
pointdistance()
{
    const int coords = 3; 
    int p1[coords]; 
    int p2[coords]; 

    ifstream ifile; 
    string path = "C:\\Users\\Joshbox\\Desktop\\points-3d.txt"; 
    ifile.open(path); 
    if (!ifile) {
        cout << "File not found: " << path << endl; 

        return -1;
    }




    while (readpoints(ifile, p1, p2, coords)) {

    }



    return 0;
}

bool readpoints(ifstream&ifile, int p1[], int p2[], int sz) {
    string data; 
    while (getline(ifile, data)) {
        for (int a = 1; a < sz; a++) {
            ifile >> p1[a]; 
        }

        cout << p1; 
    }

    return true; 
}


static int(*currentAssignment)() = pointdistance; 
int cse()
{
    return currentAssignment();
}

}

1 个答案:

答案 0 :(得分:3)

您的代码中存在多个问题。

  • readpoints总是返回true,这意味着主函数中的循环while (readpoints(ifile, p1, p2, coords))永远不会终止。
  • readpoints功能完全错误。
    • 您将整行存储到data中,然后从不使用它,这意味着此代码实际上只占一半行,从第一行开始丢弃每个备用行。
    • for (int a = 1; a < sz; a++)读取的数字比读取的数字少一个,因为您输入的数字是&#39; 3&#39;只读了2.开始索引应该是&#39; 0&#39;而不是&#39; 1&#39;。
    • cout << p1将打印数组的地址,而不是数组的内容。如果您希望此代码打印数组内容,则需要使用p1
    • 之类的结构手动迭代for(int i = 0; i < sz; i++) cout << p1[i] << ' ';

还有其他一些你可能会做的不同的事情,尽管这些是更多的&#34;最佳实践&#34;而不是&#34;你的代码失败的原因&#34;。

  • 您对using std::*的大量使用使您的代码难以阅读。虽然你没有做出更大,更常见的错误(人们写using namespace std;),你通常不应该这样做,除非你有冗长,繁琐的命名空间令牌,std没有& #39; t有资格获得&#34;漫长而繁琐的&#34;。
  • int p1[coords];:不要使用C风格的数组。在C ++ - land中,表达堆栈分配数组的首选语法是std::array<int, coords> p1;。将这些数组传递给函数时,请写下bool readpoints(ifstream & ifile, std::array<int, coords> & p1, std::array<int, coords> & p2);之类的签名。由于数组可以查询自己的大小,因此您不需要手动指定大小,并且因为数组允许使用迭代器,所以您可以编写如下代码:for(int & val : p1) ifile >> val; for(int & val : p2) ifile >> val;