从输入文件

时间:2016-10-07 23:26:27

标签: c++ arrays input

我试图从输入文件中读取数组列表,对其执行某些操作,然后打印结果。我注意到我错误地读了数组,但我无法弄清楚我做错了什么。问题似乎是以前数组中的随机数被添加到后续数组的末尾。

为了测试我的代码,我添加了几行,使其打印出代码读取的原始数组,并清楚地显示数组不再相同。我在最后包含了原始数组和输出的示例。

非常感谢任何帮助!

这是我的代码中从输入文件中读取数组的部分:

int a[50]={0};
ifstream inputFile;
string s;
stringstream ss;
string outputfile = "out.txt";
...
int n;
char c;
inputFile.open("in.txt");
while(getline(inputFile, line)){
    int stringSize = line.length();
    line = line.substr(1, stringSize - 2);

    istringstream input(line);
    string number;
    vector<int> ints;
    while(getline(input, number, ',')){
        istringstream iss(number);
        int i;
        iss >> i;
        ints.push_back(i);
    }
    copy(ints.begin(), ints.end(), array);
    int size = sizeof(array) / sizeof(array[0]);
    a1(array, size, outputfile);
}
inputFile.close();

a1()是我用我读过的数组做事的函数,但这也是我用于测试的打印函数的地方。

这是打印部分:

ofstream output;
output.open(filename.c_str(), ios::out | ios::app);
output << "Original array: ";
for (int x = 0; x < size; x++) {
    output << a[x];
    if (x != size-1) output << ", ";
}

这就是in.txt的样子:

[1, 2, 4, -1, 4, -10, 4, -19, 18, -1, -3, -4, 11, 3, -20, 19, -33, 50, 66, -22, -4, -55, 91, 100, -102, 9, 10, 19, -10, 10, 11, 11, -10, -18, 50, 90]
[12, 12, 14, -88, -1, 45, 6, 8, -33, 2, 8, -9, -33, -8, -23, -77, -89, 1, 9, 10, 92, 87]
[565, 78, 33, 9, 10, 84, 71, -4, -22, -55, -10, 76, -9, -9, -11, 76, 89, 11, 10, -33, 9]
[2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
[2]
[-1, -1, -1, -1, -1, -100, -10, -10, 100, 100, 100, 100, -100, 100, 10, -10, -1]
[12, 23, 44, -17, 12, 14, -88, -1, 45, 6, 8, -33, 2, 8, -9, -33, -8, -23, -77, -89, 1, 9, 13, -25, 10, 92, 57, 99, -22]

这就是我的out.txt现在的样子:

1, 2, 4, -1, 4, -10, 4, -19, 18, -1, -3, -4, 11, 3, -20, 19, -33, 50, 66, -22, -4, -55, 91, 100, -102, 9, 10, 19, -10, 10, 11, 11, -10, -18, 50, 90, 0
12, 12, 14, -88, -1, 45, 6, 8, -33, 2, 8, -9, -33, -8, -23, -77, -89, 1, 9, 10, 92, 87, 91
565, 78, 33, 9, 10, 84, 71, -4, -22, -55, -10, 76, -9, -9, -11, 76, 89, 11, 10, -33, 9, 87
2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 11
2, 3
-1, -1, -1, -1, -1, -100, -10, -10, 100, 100, 100, 100, -100, 100, 10, -10, -1, 3
12, 23, 44, -17, 12, 14, -88, -1, 45, 6, 8, -33, 2, 8, -9, -33, -8, -23, -77, -89, 1, 9, 13, -25, 10, 92, 57, 99, -22

1 个答案:

答案 0 :(得分:0)

我将a[100]={0}移到了循环内部,正如其中一条评论所暗示的那样,这似乎解决了这个问题。

我现在可以正确使用数组,但我的输出总是在数组末尾添加0。现在这是一个小问题,不再影响我的代码。