Vector out of bounds

Pages: 12
I cant see where am accessing beyond myVec vector in this function herebelow. Where could be the problem ?
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
void  Display_file  ( std::vector<std::string> &myVec) {

std::string line = "";   //variable to hold lines being read from file
std::fstream inFile("Lands File.txt");   //opening text file in read mode  by default 

 //unsigned int i;
 
   while (std::getline(inFile, line)) {
		//parsing the file lines 
		
          myVec.push_back(line);  //reading a line into a vector (temporary in memory)
    
   //unsigned int size =   
  for ( size_t i= 0; myVec.size (); i++) 

cout<<myVec.at (i);    	
cout<<endl; 
	
		inFile.clear (); //move to newline
	  }

 	system ("pause");
	inFile.close();
    
	 return ;
}


The error message:
 
Microsoft C++ exception: std::out_of_range at memory location 0x0022F560.
Last edited on
Hi too. Here is the error displayed at debugger
1
2
3
>	msvcr110d.dll!_CxxThrowException(void * pExceptionObject, const _s__ThrowInfo * pThrowInfo) Line 152	C++
 	msvcp110d.dll!std::_Xout_of_range(const char * _Message) Line 25	C++
The while loop is the problem. It also reads one line then throws the exception.
File contains comma separated records. I have even tried parsing through the stringstream object and ignoring the comma (,) but throws same error.

File has lines with strings like these:

name of individual, identification Number, property number, Location detail
Post the smallest complete program that illustrates your problem.

By the way your debugger should be able to tell you exactly where it detects the problem and then you should be able to look at the variables at the time of the crash.

Also post a very small sample of your actual input file.

The code you posted shouldn't even compile since it has mismatched braces.

Also note that several of your comments are incorrect. For example an fstream opens the file for read write access by default. If you're only going to be doing input I recommend you use an ifstream instead of an fstream. And inFile.clear() just resets the stream error state to the good state, it doesn't do anything with the underlying file pointer.

Last edited on
I placed the inFile.clear(); later when i encountered the problem, had read it as a solution from another thread.

I have removed it but the error persists.
Last edited on
I think the problem is in line 14.

for ( size_t i= 0; myVec.size (); i++)

myVec.size is >0, so the middle part of the for statement will always return true, and the loop will never terminate.

You want to replace the middle part with i < myVec.size();
Hi Jlb, i had first tried the ifstream, then replaced with fstream when i saw no error in locating the file.

There are several lines of this kind:
1
2

Surname:Gilbert, OtherNames:Nduva Muli, Land Number:098765, KRA PIN:12345, ID card No.:1111111, address:125, County:Muranga, District:kangema, Division:Muguru, Location:Gacharaigu, Sublocation:Kiamara


I want to read and display them and would wish that the comma between them is not displayed to screen (but have not seen such a solution anywhere).
Last edited on
I am stepping through the debugger and observed an error could be here (though not sure):
1
2
3
4
5

	__declspec(noreturn) void _Xran() const
		{	// report an out_of_range error
		_Xout_of_range("invalid vector<T> subscript");
		}

Could it be the access at.(i) ?
Yes the error is at cout<<myVec.at (i);
Last edited on
closed account 5a8Ym39o6, that reads to the first comma then stops
but have not seen such a solution anywhere

That's why you're learning programming, so that you can write your own solution.

I am stepping through the debugger and observed an error could be here

No, that code seems to be somewhere in your compiler's implementation of the standard library. The problem will be somewhere within your code.

Yes the error is at cout<<myVec.at (i);

And what is the value of i at the time of the crash?

Did you read doug4's post? Did you fix the issue he pointed out?

I would be very very careful taking advice from closed account, someone should really close that account, he seems to give a lot of bad advice.
Kindly, i have completely edited the question. The function below is doing. The problem is that it is appending (thus duplicating a record that i want to modify). What do i do to overwrite the recorded searched and leave the others intact ? Read the commentary in the code below to get clearly what i am doing.


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
57
58
59
60
61
62
63
64
65
66
67
68
69
70

struct LandDetails { // declaring a class
public:
	string Surname,OtherNames,LandNum,KraPin, OwnerIdCard, address, LandCounty,LandDist,
	LandDiv,Landloc,LandSubloc;

void modify_record ();   //function will read a file into a vector, a line is searched that correspond user input, the record found is modified by a string, the file so 
                         //modified is passed to another vector and written back to file.
                    //The function is doing, but appends the record at end of file (duplication of record), 
                  //  how do i modify the function to overwrite that record only and leave the other records intact ?
	
};

int main()
{
LandDetails openner;
	openner.modify_record ();	
	system ("pause");
	return 0;
}

void LandDetails:: modify_record ()
{
	LandDetails obj;   
       std::fstream inFile("Lands File.txt");  //open text file in read mode

                std::cout << "Please enter the individual's Surname whose Land you want to search "<<endl;
               std::getline (cin, obj.Surname);
               std::cout<<"Enter owner KRA pin\n";
	        getline (cin,obj. KraPin);

	std::string::size_type found;
	std::vector<std::string> old_file;   //will hold old file being read to memory
	std::vector<std::string> modified_data;    //will hold modified file containing 
	string new_line = "Registrar : Transferred";     //a string that will be added to line
	std::string line = "";
	
	if (!inFile)  {     std::cout << "File not opened\n"; return; }
	      
	  while (std::getline(inFile, line))  //reading file line by line into a string variable
    {
			
			{ old_file.push_back (line); }   //reading into a vector container
			
					inFile.close ();
	
	    for (size_t i =0;i<old_file.size ();i++)         //searching for the record through the file already in memory
	    {
            if ((found = line.find (obj.Surname , 0)) && (found = line.find (obj.KraPin,0) !=string::npos))
	
             std::cout <<"\n"<<obj.Surname <<" of KRA Number "<<obj.KraPin<<" record found with the following details: \n\n"<< line << '\n';
		
		//after record is found, it is concatenated with the string value
		line =line + "," + new_line;

		modified_data.push_back (old_file [i] +line );     //am including the modification
           }
	  
	  	 ofstream writer ("Lands File.txt", ios::app);   //if i omit the ios::app flag, everything gets overwritten and only
		                                                 // the rectified record is written to file----advise since i wont remove this flag
		 if (!writer) {cout<<"Failed to open file for writing"; }

	   for (size_t j=0; modified_data.size ();j++)      
	        {	  writer<<modified_data [j]<<endl<<endl;     } //then writing back everything to file      	 

	 writer.close ();

    }
}
Last edited on
You really really need to work on your indentation. As presented your code is very difficult to read.

Next you should consider more functions. For example the code inside several of your case statements could/should be moved to some functions, IMO. IMO if you need to add braces to a case statement you should consider functions and/or if/else statements instead.

Next no matter how you open your files you can't just add information to the middle of a file, you can only overwrite existing information. If you want to add information you need to rewrite the file with the added information.
> Is it allowed to parse a file in write mode, so that when you strike a record
> you can add text to it ?
No, you'll overwrite the next record.
Instead, load the entire file in a container, modify the elements in the container as you please, then dump the entire container.

> I am getting this problem here while (std::getline(openFile, liner1));.
¿what problem? ¿where? I don't see that line anywhere in the code you've posted.

> I am opening the first file in read mode, i then search a record using...
¿what (not how) are you trying to accomplish?

> This is the runnable fragment
First, learn to indent.
Second, that is not runnable. We are missing your input files.
@Mwangi Elijah

This is a question that has been going on in one form or another since you joined in Dec 2015. Why have you not taken the advice offered? Instead you seem to make new Topics all the time, and ignore previous advice, including from 3 days ago.

http://www.cplusplus.com/forum/general/195601/#msg940276

http://www.cplusplus.com/forum/general/183557/#msg898346
Last edited on
Yes TheIdeasMan, ....i have not wanted to copy paste but to learn....i have learnt alot here, and made corrections.....and that is why i have been writing the code after reading different posts ...... was doing a school project (which turned to be a big one - touching four istitutions thus different fuctionalities- all are interfacing with this database, thus had to take time build it ) and have been trying to enquire so i may be informed appropriately. I am completing the project today.

Would you kindly look at that my most recent comment/ question ( in this thread) i have edited about the void modify_record () function and advise how i can remove that redundancy when i modify a record please ?
Last edited on
closed account (48T7M4Gy)
Sounds like dreaded group work. Where are u studying Mwangi? What year? :)


Mwangi Elijah wrote:
...i have learnt alot here, and made corrections.....


Not really, your code is very similar to what is was back in January.

i have edited about the void modify_record () function and advise how i can remove that redundancy when i modify a record please ?


I gave you advice about that the other day. Why have you ignored it?
closed account (48bpfSEw)
There are only 3 problems during learning a new skill:

1. unknown words or symbols

if one can not explain the words or symbols which the subjects is defined with its own words he/she will run in problems of understanding.

2. lack of mass or dimension

the individuum learns with more then one sence: hearing, feeling, touching...)
if only one sense is used during learning the learner will fall in a lack of sense and the phenomenon is: angry, fear, confussion

3. the gradient

there are steps or levels to the top. if one skips some levels he/she will fall down. learning is like climbing on a mountain: you have to secure yourself step by step.




There are a lot of good stuff about how to study in the web:
e.g.

https://www.google.de/search?q=study+techniques+pdf&ie=utf-8&oe=utf-8&client=firefox-b&gfe_rd=cr&ei=-hawV_yYOc3j8wflloHwDA

http://www.macmillanlearning.com/Catalog/uploadedFiles/Content/Worth/Microsites/ForeWords/Himsel_Ch01_Final_Color%20(2).pdf

jlb said:
You really really need to work on your indentation. As presented your code is very difficult to read.

You really should take his advice. Below is your code, indented to match the actual structure. As you can see, the loop at line 50 contains all the code from there to the end of the file. This does not appear to be what you intended.

Also line 66 is outside the "if" statement. That's probably not what you intended.

You never clear the line variable. So once it's set, line 68 will append it to every subsequent line.

Also, line 58 is wrong. That expression is true if found != 0. You need to check whether found != string::npos

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
struct LandDetails
{				// declaring a class
  public:
    string Surname, OtherNames, LandNum, KraPin, OwnerIdCard, address, LandCounty,
	LandDist, LandDiv, Landloc, LandSubloc;

    //function will read a file into a vector, a line is searched that
    //correspond user input, the record found is modified by a string,
    //the file so modified is passed to another vector and written
    //back to file.  The function is doing, but appends the record at
    //end of file (duplication of record), how do i modify the
    //function to overwrite that record only and leave the other
    //records intact ?
    void modify_record();

};

int
main()
{
    LandDetails openner;
    openner.modify_record();
    system("pause");
    return 0;
}

void
LandDetails::modify_record()
{
    LandDetails obj;
    std::fstream inFile("Lands File.txt");	 //open text file in read mode

    std::cout << "Please enter the individual's Surname whose Land you want to search " <<
	endl;
    std::getline(cin, obj.Surname);
    std::cout << "Enter owner KRA pin\n";
    getline(cin, obj.KraPin);

    std::string::size_type found;
    std::vector < std::string > old_file;	 //will hold old file being read to memory
    std::vector < std::string > modified_data;	 //will hold modified file containing 
    string new_line = "Registrar : Transferred";	//a string that will be added to line
    std::string line = "";

    if (!inFile) {
	std::cout << "File not opened\n";
	return;
    }

    while (std::getline(inFile, line)) {	 //reading file line by line into a string variable
	{
	    old_file.push_back(line);
	}					 //reading into a vector container

	inFile.close();

	for (size_t i = 0; i < old_file.size(); i++) {	//searching for the record through the file already in memory
	    if ((found = line.find(obj.Surname, 0))
		&& (found = line.find(obj.KraPin, 0) != string::npos))

		std::cout << "\n" << obj.
		    Surname << " of KRA Number " << obj.KraPin <<
		    " record found with the following details: \n\n" << line << '\n';

	    //after record is found, it is concatenated with the string value
	    line = line + "," + new_line;

	    modified_data.push_back(old_file[i] + line);	//am including the modification
	}

	ofstream writer("Lands File.txt", ios::app);	//if i omit the ios::app flag, everything gets overwritten and only
	// the rectified record is written to file----advise since i wont remove this flag
	if (!writer) {
	    cout << "Failed to open file for writing";
	}

	for (size_t j = 0; modified_data.size(); j++) {
	    writer << modified_data[j] << endl << endl;
	}					 //then writing back everything to file            

	writer.close();

    }
}

Pages: 12