Ask your own question, for FREE!
Computer Science 20 Online
OpenStudy (pradius):

C++ question Im learning to use functions. In this code, whenever I type in a full name, just the first name is displayed in the system. Any reason why?

OpenStudy (pradius):

/****************** ***TEST C++ FILE*** ******************* *****Pradius****** ******************/ #include <iostream> #include <string> using namespace std; class Functions { public: void SetName(string x){ name = x; } string GetName(){ return name; } private: string name; }; int main() { string name; Functions fobject; cout << "What is your name\n"; cin >> name; fobject.SetName(name); cout << "Your name is " << fobject.GetName() << endl; return 0; }

OpenStudy (anonymous):

bro .. i don't know c++..i know c and java. so i think while inputing string as name , it takes the space as end of character and that's why it is not storing any character after space. becoz in c , when we write scanf("%s",s); then it stores any characters before space.

OpenStudy (pradius):

mmm well that's not happen in Java... so how to solve it?

OpenStudy (anonymous):

as i said.. i know c and java .. in c , you can use gets(str); in place of scanf()....

OpenStudy (anonymous):

you can use getline(cin, yourstring);

OpenStudy (anonymous):

What infinity said. When using stream operators in c++, it only reads up to the first whitespace.

OpenStudy (anonymous):

#include <iostream> #include <string> using namespace std; class Functions { public: void SetName(string x){ name = x; } string GetName(){ return name; } private: string name; }; int main() { string name; Functions fobject; cout << "What is your name\n"; getline(cin,name); //modification fobject.SetName(name); cout << "Your name is " << fobject.GetName() << endl; return 0; }

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!