How can I take a user's first and last name with std::cin and print it back out with only using one variable? I'm new to C++ but have an extensive understanding of Java and general programing. Here is my code:
#include %26lt;iostream%26gt;
#include %26lt;string%26gt;
using namespace std;
int main() {
string user;
cout %26lt;%26lt; "Please enter your name: ";
cin %26gt;%26gt; user;
cout %26lt;%26lt; "\nWelcome " %26lt;%26lt; user %26lt;%26lt; "!" %26lt;%26lt; endl;
system("pause");
return 0;
}
The problem is that this program only prints the first string entered.
In C++, what is the best way for me to read a users string input....?
The problem is cin terminates the string when it encounters whitespace. So you have to use another method....
#include %26lt;iostream%26gt;
#include %26lt;string%26gt;
using namespace std;
int main() {
string user;
cout %26lt;%26lt; "Please enter your name: ";
// this will allow you to input spaces
getline(cin,user);
cout %26lt;%26lt; "\nWelcome " %26lt;%26lt; user %26lt;%26lt; "!" %26lt;%26lt; endl;
system("pause");
return 0;
}
Reply:Cause you only input one string and output the same thing. Concatenate strings.
In java, cause I am forgetting C++ at the moment
String fullName = fName +lName;
System.out.println(fullName);
OR
System.out.println(flName + " " + lName);
Reply:Using this
#include %26lt;iostream%26gt;
using namespace std;
int main() {
char buffer[100]; //buffer size 100
cout %26lt;%26lt; "Please enter your name: ";
cin.getline(buffer,101 ); //terminate input when carriage return hit, can specify the terminate charater in the third argument by default it's \n
string user = buffer;
//might want to do tokenizing here if you have multiple input
cout %26lt;%26lt; "\nWelcome " %26lt;%26lt; user %26lt;%26lt; "!" %26lt;%26lt; endl;
system("pause");
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment