What is wrong with this piece of code?

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
string* readData(string []);
void displayMenu(string []);

int main()
{
	string *array=new string[11];
	
	
	
    displayMenu(readData(array));


	system("pause");
}
string* readData(string array[])
{
	ifstream read;
	read.open("a.txt");

	int i=0;
	
	string a;
	while(getline(read, a))
	{
        array[i]=a;
		i++;
	}

	read.close();





	return array;
}

void displayMenu(string array[])
{
	for(int i=0; i<11; i++)
	{
		cout<<array[i]<<endl;
	}

	

	
}





It gives an empty output, instead of printing the contents of file stored as a.txt, what exactly is the problem with this?
It is working correctly for me. Are you sure youre textfile is in the right location? It should be in the same folder as your C++ project.

You should always check to see if the file you are trying to open exists or can be openend at all.
(see: http://www.cplusplus.com/reference/fstream/ifstream/is_open/ for more detail)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
string* readData(string array[])
{
    ifstream read;
    read.open("a.txt");
     if(!read.is_open())
        cout << "something went wrong!" << endl;
    else
    {
        int i=0;
        string a;
        while(getline(read, a))
        {
            array[i]=a;
            i++;
        }
        read.close();        
    }
    return array;
}
Last edited on
Silly Mistake! text file was named a.txt.txt
lol
Got it now!
Thanks!
Last edited on
Topic archived. No new replies allowed.