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?
/****************** ***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; }
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.
mmm well that's not happen in Java... so how to solve it?
as i said.. i know c and java .. in c , you can use gets(str); in place of scanf()....
you can use getline(cin, yourstring);
What infinity said. When using stream operators in c++, it only reads up to the first whitespace.
#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; }
Join our real-time social learning platform and learn together with your friends!