program has stopped working

I have this kind of problem: 1.Program open file called "abc.txt". 2.In while loop i save each line from file abc.txt to variable text and then, from text to ArrSent[n]. I have no idea why program has stopped working. Plz help me.

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
 #include<iostream>
#include<string>
#include<fstream>

using namespace std;

void function()
{
	string text;//variable to save text from file
	ifstream myfile("abc.txt");//reading from file called abc.txt

	long long int n=0;//numbers of lines
	string *ArrSent= new string[n];//Array which saves all sentences 


	if (myfile.is_open())
	{
		//cout <<"myplik.good()= "<< myfile.good() << endl;
		
		while (myfile.good())
		{	
				getline(myfile, text);
				ArrSent[n] = text;
				n++;
		}
		cout << "n= " << n << endl;

		myfile.close();
	}

}


int main()
{
	function();
	system("pause");
	return 0;
}
Last edited on
1
2
long long int n=0;//numbers of lines
string *ArrSent= new string[n];//Array which saves all sentences 
It is illegal and your compiler should at least warn you about it. You are creating array which holds 0 elements. And still you are trying to write something into it.
I changed the code but still there is sth wrong..In file called abc.txt there is following text:

sample text
sample text
sample text
sample text
sample text

I have this kind of problem: after end of program appears alert
with message: vector subscript out of range. I have no idea why..

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
    #include<iostream>
    #include<string>
    #include<fstream>
    #include<vector>
    
    using namespace std;
    
    void function()
    {
    	string text;//variable to save text from file
    	ifstream myfile("abc.txt");//reading from file colled abc.txt
    
    
    	
    
    	vector<string> ArrSent;
    
    	if (myfile.is_open())
    	{
    		//cout <<"myplik.good()= "<< myfile.good() << endl;
    		
    		while (myfile.good())
    		{	
    				getline(myfile, text);
    				ArrSent.push_back(text);
    		}
    		
    
    		myfile.close();
    	}
    	for (int i = 0; i <= ArrSent.size(); i++)
    	{
    		cout << ArrSent[i] << endl;
    	}
    
    }
    
    
    int main()
    {
    	function();
    	system("pause");
    	return 0;
    }
Last edited on
i <= ArrSent.size();
If your vector has size of, say, 2, you will try to access indexes 0, 1 and 2. Explain, how did you get 3 elements from size 2 array?

Use i < ArrSent.size();. It is common pattern with access to indexed containers.
Topic archived. No new replies allowed.