简体   繁体   中英

C++ Writing to array in function

The problem is that the contents of the array "data" change to these seemingly random numbers when I try to access them in main, after the "ReadFile" function has run. The numbers are the same for the same input. I think it has something to do with pointers or references, but I dont what it is.

Examples:

INPUT:

4000

-2500

12

-600

-700

3000

OUTPUT:

Number of lines: 6

2686316

4706252

1

1991562344

4661696

4703488

CODE:

#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;
const int MAXN = 100;

string ReadFileName(string& filename) {
    cout << "The name of the file: ";
    cin >> filename;
    return filename;
}

int ReadFileLength(int& linecount, string filename) {
    ifstream f;
    bool error;
    do {
        ReadFileName(filename);
        f.open(filename.c_str());
        error=f.fail();
        if(error) {
            cout << "Error while tying to open file." << endl;
            f.clear();
        }
    }
    while (error);

    int tmp;
    while (f >> tmp) {
        linecount++;
    }
    f.close();
    return linecount;
}

void ReadFile(int* data, int linecount, string filename) {
    ifstream f;
    f.open(filename);
    for(int i=0; i<linecount; i++)
        f >> data[i];
    f.close();
}

int main() {
    int data[MAXN];
    bool error;
    int readmethod;
    int linecount = 0;
    string filename;

    do {
        message1();
        cin >> readmethod;
        error = cin.fail() || ((readmethod!=1) && (readmethod!=2));
        if (error) {
            cout << "Wrong Data!" << endl;
            cin.clear(); string tmp; getline(cin, tmp, '\n');
       }
    }
    while(error);

    if (readmethod==1) {
        ReadFileLength(linecount, filename);
        ReadFile(data, linecount, filename);
    }
    else {
        //Implement later
    }

    cout << "Number of lines: " << linecount << endl;

    for (int i=0; i<linecount; i++) {
        cout << data[i] << endl; //THIS IS WHERE TO PROBLEM SHOWS UP
    }

    return 0;
}

I have omitted "message1" and "ReadFileLength" functions from the code because they are working fine.

My crystal ball says:

Your ReadFileLength not only calculates the length, but also asks for a filename.
Unfortunately you forgot to pass that parameter as a reference ( std::string& filename ), or forgot to assign to the parameter.
Thus, the filename is still the empty string when the function returns, and opening a file with that name is bound to fail.

BTW, asking for a filename and retrieving the length of a file sounds like two unrelated functions that both return a single value, not one function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM