I Have No Idea How To Make These Dynamic Arrays Work

I'm trying to fill up an array with characters from a file and then pass it back to the main function so I can sort of juggle all the information I'll be gathering from different files between functions.

At first I was trying to make the function return an array to the main function, but I couldn't get valid information that way. So I used pointers to point at arrays, but I couldn't get that to work. Then I was trying to use pointer arrays using dynamic memory and I still can't get it to work. They end up spitting out junk data. So I tried cheating and making the pointers as global variables and so I've humbled myself to ask for help here

Oh, and in case you need to know; the "answers.txt" file is set up so the first line has the number of questions that were on the test, and the subsequent lines are the actual answers (A-E).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <fstream>
#include <string>

using namespace std;
int numberOfQuestions;
char *answers;

int AnswerGet();

int main() {

    AnswerGet();
    delete[] answers;
}

int AnswerGet() {

    ifstream solutions;
    solutions.open( "answers.txt", ios::in );
    if ( solutions ) {
        solutions >> numberOfQuestions;
        if ( numberOfQuestions >= 100 ) {
            cout << "Too many questions! Poor students!";
            return 1;
        }
    }
    else {
        cout << "Answer key failed to open";
        return 1;
    }
    answers = new char [numberOfQuestions];
    for ( int i = 0; i < numberOfQuestions; i++ ) {
        solutions >> *answers;
        answers += 1;
        cout << &answers << endl;
    }
    solutions.close();

}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>
#include <fstream>

// http://www.mochima.com/tutorials/strings.html
std::string AnswerGet()
{
    std::ifstream solutions( "answers.txt" );

    std::string answers ;

    int numberOfQuestions ;
    solutions >> numberOfQuestions ;

    if( numberOfQuestions >= 100 )
        std::cout << "Too many questions! Poor students!\n" ;

    else
    {
        for( int i = 0 ; i < numberOfQuestions; ++i )
        {
            char ans ;
            solutions >> ans ;
            answers += ans ;
        }
    }

    return answers ;
}

int main()
{
    std::string answers = AnswerGet() ;

    std::cout << "number of questions: " << answers.size() << '\n' ;
}
Topic archived. No new replies allowed.