I try to search the similar symptoms on the web and also forum regarding this matter. I wish to create system to input student info( i start with name first)
1)when i compile, it just stopped working before i try to key in student name. I wish to put the names into an array as i will later add more info in it.
2) when i wish to input 2 student's names, it output "Student's name:" twice which is very weird.
I had try to break down to find my problem which i find that my getline has no problem. I couldn't detect the bug. Thanks for helping out.
First of all 'namePtr' should be initialized to null on construction of your Student object.
Line 18: Student::Student() : namePtr(NULL)
On line 25 you hide 'namePtr' by declaring it again this time as a local variable.
Instead write: namePtr=new string[size]; // NOTE: without preceding string*
Thanks... It solved the problem for the console stopped working. =)
but i still encountered a problem like this if i input for the amount of student info i wish to insert.
Amount of student's registration(s) :
3
Student's name :
Student's name :
jessy(input)
Student's name :
jessica(input 2)
jessy
jessica
--program end---
why is that so? it skipped my first attempt to insert data...
Line 24 reads a numeric value but unfortunately doesn't remove the line end from the stream.
after line 24 insert cin.ignore(); which should solve your problem.
And while doing so on line 28 you should add Student::Student() : namePtr(NULL), size(0) // NOTE: size must also be initialized . Better always initialize your member variables
Why do you need to dynamically allocate a std::string? Don't do that.
1 2 3 4 5 6 7 8 9
class Student
{
private:
string name;
int size;
public:
...
};
Now just use the string normally. The string class handles all the dynamic character array allocations and deallocations for you.
[edit 2] Oops! I get it. Why not use a vector<string>?
As to the problem you are having, it is because you are mixxing formatted and unformatted input.
The user will always press ENTER at the end of every input.
Hence, you must always extract that '\n' from the end of every input.