从文件读入数组后,为什么会得到奇怪的值?

时间:2015-10-23 16:25:43

标签: c++ arrays file file-io input

我是C ++的新手。基本上我要做的是将文件读入任何数组并显示它,但是当运行下面的代码时会出现垃圾值。究竟我错过了什么?

#include "stdafx.h"
#include<iostream>
#include<fstream>

using namespace std;

void main() {
    int array_size = 1024;
    char*array = new char[array_size];

    int position = 0;
    ifstream fin("Map.txt");
    if (fin.is_open()) {
        while (!fin.eof() && position < array_size) {
            fin.get(array[position]);
            position++;
        }
        array[position - 1] = '\0';

        cout << "Displaying array......" << endl << endl;

        for (int i = 0; array[i] != '0'; i++) {
            cout << array[i];
        }
    } else {
        cout << "File could not be opened" << endl;
    }
}

1 个答案:

答案 0 :(得分:1)

主要问题是您的for循环条件错误。您不应该将array [i]与'0'进行比较,因为这是ASCII字符0,其值实际为48。

您希望将array [i]与“null-terminated”字符进行比较,“<0>的值 0。

相关问题