Sunday, July 26, 2009

Problem with c++ code - program only runs correctly the first time.?

A program I wrote in c++ to store contact information to a text file only works correctly the first time through. The second time I try to run the file, I can only type in the file name and then hit [enter]. but nothing happens.


please help

Problem with c++ code - program only runs correctly the first time.?
Ok, there's two problems here that I can see.





1) All your getline calls inside your main function should be getting input from "input", not from "cin". Fix that, and you'll get your data from the file.





Example:


getline(cin, contact[i].firstname);





should be changed to





getline(input, contact[i].firstname);





Also, in the code you posted, you do a getline to get the firstname twice. When you fix your getlines, make sure you're only doing that once or you'll throw off your data reading. I don't know if that was caused by copy/pasting the code into Yahoo or not, but just giving you the heads up.





2) It's not a good idea to declare your contact array using a dynamic variable. I'm referring to the following line:





Person contact[arraySize];





You should do one of two things here. Either assume a maximum number of "Persons" you're going to be dealing with (e.g., 100) and just declare the array to that size, or use a pointer to create a dynamic array. The easiest solution is to assume a value, the best solution is to use a dynamic array.





Hope that helps!
Reply:Check how you initialize your variables. It may work the first time only because those memory locations happen to be zero. After that whatever is in there will remain and interfere unless you are careful with clearing them before using them.


No comments:

Post a Comment