Writing 2 names (with spaces) in C++ (cin command) - c++

I am beginner to the C++ and was trying to build first codes. Right now I'm trying to learn cin command but there is a problem. When I use this code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
string surname;
cout<<"Please enter your name: ";
cin>>name;
cout<<"Please enter your surname: ";
cin>>surname;
cout<<"Your name: "<<name <<endl;
cout<<"Your surname: "<<surname;
}
The output is:
Please enter your name: aaa bbb
Please enter your surname: Your name: aaa
Your surname: bbb
So when I use 2 names in the 'name' variable, this happens. But when I just write 'aaa' in the name and 'bbb' in the surname, it works perfectly fine:
Please enter your name: aaa
Please enter your surname: bbb
Your name: aaa
Your surname: bbb
What do I have to do? Thanks.

Use the getline function:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name, surname;
cout << "Please enter your name: ";
getline(cin, name);
cout << "Please enter your surname: ";
getline(cin, surname);
cout << "Your name: " << name << endl;
cout << "Your surname: " << surname;
}
cin reads just till the first space, but getline reads till the first new line. That means that cin only takes the first word, and the next word "rests" unpicked on the console. When the next cin comes, it takes that "resting" word.
You have to include the #include<string> header when using function getline. You specify the input type as first argument (that's what you put in the parentheses – in our case cin), and as second argument is the string where you want to save that value. For example, getline(cin, input);. If you don't use namespace std;, you must also specify the namespace, so like this: std::getline(std::cin, input).
If you are still learning C++, you won't understand this, but maybe a little later: there are actually two forms ("overloads") of getline function: one is like I said before (istream& getline (istream& is, string& str, char delim);), but another also uses the 3rd parameter (istream& getline (istream& is, string& str);), like this: getline(cin, input, ';');. With that code, the input stream ends the input at the first semicolon. Note the ' sign, not " sign!

Related

How do I get the first x characters of a string to be measured and printed out?

I've been assigned a problem at school and it goes as follows:
Write a program that creates a login name for a user, given the user's
first name, last name, and a four-digit integer as input. Output the
login name, which is made up of the first five letters of the last
name, followed by the first letter of the first name, and then the
last two digits of the number (use the % operator). If the last name
has less than five letters, then use all letters of the last name.
The sample output is:
Enter first name: John
Enter last name: Doe
Enter last 4 digits of social security number: 8457
Your login name: DoeJ57
So far this is my code:
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main()
{
string firstName;
string lastName;
int ssn;
int lastTwo;
char firstCharacter;
string lastNameLength;
cout << "Enter first name:";
cin >> firstName;
cout << "Enter last name:";
cin >> lastName;
cout << "Enter last 4 digits of social security number:";
cin >> ssn;
firstCharacter = firstName.front();
lastTwo = (ssn % 100);
lastNameLength = lastName.length();
cout << lastNameLength;
return 0;
}
I tried measuring the length of the last name for it to print out but now I'm stuck on how to get the last name sized and then printed, any guidance is appreciated.
std::string has a substr() method for extracting a portion of the string. If you ask it for the 1st 5 characters, and the string is shorter than 5 characters, then the entire string will be returned. Which is exactly what your instructions ask for.
Try something more like this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string firstName;
string lastName;
int ssn;
cout << "Enter first name:";
cin >> firstName;
cout << "Enter last name:";
cin >> lastName;
cout << "Enter last 4 digits of social security number:";
cin >> ssn;
cout << lastName.substr(0, 5) << firstName.front() << ssn % 100;
return 0;
}
Online Demo

New to C++ and wondering what getline() and cin are doing in my code

#include <iostream>
#include <string>
using namespace std;
void computeFeatures( string );
int main(int argc, const char * argv[])
{
string name;
cout<< "Please enter your full name" << endl;
cin >> name;
cout << "Welcome" << name << endl;
cout << "Please re-enter your full name: ";
getline(cin, name);
cout << "Thanks, " << name << endl;
return 0;
}
The output is this:
Please enter your full name
John Smith
WelcomeJohn
Please re-enter your full name: Thanks, Smith
I guess my question is why does cin print out the first name and why does getline() print the second name. Is there a way to print both?
cin only reads the first word, getline reads until it gets an /n. So if you want to print both you should do this:
cout<< "Please enter your full name" << endl;
getline(name);
cout << "Welcome" << name << endl;
cout << "Please re-enter your full name: ";
getline(name);
cout << "Thanks, " << name << endl;
Also, when you say getline(cin, name) you first read the first name with and then the rest of the input with getline and you only put the last name in 'name'because you already read the first name with cin, but didn't place this in 'name'.
When you read input with cin >> name the input stops at the first space (blank, tab, newline). So it reads only "John".
When you then call getline() it continues where it stopped, starting at "Smith" and reading until the end of this line.
If you want to start reading with >> but then skip the rest of the input until the next line, you can use: cin.ignore(SIZE_MAX, '\n');
cin takes the first word as it's input and the second one which is separated by space is waiting in input buffer. Thus the getline() gets the last name automatically and doesn't even wait for any user input.
You should only use getline(cin,name) if you want both first and last name in string variable name.

How can i write information words into a file with c++

Am trying to Write file into a file but once i enter the name it prompts a click to close
this is mine code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void login(){
char name, email, address;
ofstream myfile;
myfile.open ("user.dll");
cout << "Enter Name : ";
cin >> name;
cout << "Enter Email : ";
cin >> email;
cout << "Enter Address : ";
cin >> address;
myfile <<name << email << address << endl;
}
int main()
{
login();
system("pause");
return(0);
}
and the is the display
You should be entering std::strings not chars. Change
char name, email, address;
To
string name, email, address;
Why did it seemingly skip your 2nd and 3rd cin prompts?
You used std::cin to read the input from the stream. During the first prompt, you entered "chrys", which added 5 chars to the stream.
If you followed the operations of cin you basically had:
name = 'c'
email = 'h'
address = 'r'
If you would have used getch() for example, this would have been obvious. If you were set on char you would have had to use the C-like method of reading into a char[], but since this is C++, std::string is a much better option for your case.

While loop fail, when reading int and string C++

I'm trying to read multiple Strings and ints from the user. I want to take pairs of Name and Age and keep doing it until the user types in "done". But my do-while crashes early on, and i can't figure out why?
int number;
string name;
do
{
cout << "Your name: " ;
getline(cin, name);
cout <<name<< " age: " ;
cin >> number;
}
while (name!="done");
Edit: Also after entering "done", i have to enter "done" also on age, why is that?
I tried to run your program in VS 2010, and even when I entered a valid number, the program would, to my surprise skip reading the next name.
It seems to me that cin >> number doesn't swallow the '\n' I naturally entered after the number.
I attempted adding a call to getchar() after each cin >> number and the program suprisingly started working as expected.
So the conclusion is, that you should clean()/ignore() after cin >> number even after the number entered was OK, or resort to using getline() (and then parsing) for reading numbers.
If you want not to input "done"'s age then you have to break out of the loop immediately after it's entered. My final code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int number;
string name;
while(true)
{
cout << "Your name: " ;
getline(cin, name);
if(name == "done")
break;
cout <<name<< " age: " ;
cin >> number;
cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
}
}
If someone enters an invalid age, i.e. something that isn't a number, you need to clear the flags of your cin, and also flush any remaining characters.
if( !(cin >> number )
{
cin.clear();
}
cin.ignore( std::numeric_limits<streamsize>::max() );
If it does read a number then you also need to ignore the newline after it.
Use the std namespace
This way
int number;
string name;
do
{
std::cout<<"Your name: " ;
std::cin>>name;
std::cout<<name<<" age: " ;
std::cin>>number;
}
while (name!="done");
Or this
using namspace std;
int number;
string name;
do
{
std::cout<<"Your name: " ;
std::cin>>name;
std::cout<<name<<" age: " ;
std::cin>>number;
}
while (name!="done");
#include <iostream>
#include <string>
int main ()
{
std::string name;
int age;
while (true)
{
std::cout << "Please enter your name: ";
std::cin >> name;
if ( "done" == name )
break;
std::cout << name << ", please enter your age: ";
std::cin >> age;
std::cout << name << ", you are " << age << " years old\n";
}
std::cout << "Bye.\n";
return 0;
}
Mixing use of getline() and >> can be problematic. Best to just avoid it if you can. You could also use getline() for both, and convert the int using a stringstream, or possibly atoi(), but I don't like that much.
Because you give it a string while it expect an int as age.
At the end of the first iterate, as you typed the Enter key to input the age, an extra newline was taken into the cin. So in the second iterate, the newline showed up as an empty line, causing the name to be set as an empty string. Then the program wanted an int as age. If you are not careful enough, you would input a string and cause the program crash.
One suggestion:
To replace:
getline(cin, name);
with:
do {
getline(cin, name);
} while (name.empty());

Why isn't my string splitting like it should?

I'm working on a project of splicing an inputted string of a name, and for some reason it's not working. Part of it is code copied from my book that supposedly works, so I'm stuck. Am I doing something wrong?
#include <iostream>
#include <string>
using namespace std;
void main()
{
string name;
int index;
cout<<"Please enter your full name. ";
cin>>name;
cout<<"\n"<<endl;
index = name.find(' ');
cout<<"First Name: "<<name.substr(0, index)<<" "<<name.substr(0, index).length()<<endl;
name = name.substr(index+1, name.length()-1);
index = name.find(' ');
cout<<"Middle Name: "<<name.substr(0, index)<<" "<<name.substr(0, index).length()<<endl;
name = name.substr(index+1, name.length()-1);
cout<<"Last Name: "<<name<<" "<<name.length()<<endl;
}
Most peoples' names consist of at least two words. This will only get one of them:
cout<<"Please enter your full name. ";
cin>>name;
istream operator>> is whitespace delimited. Use getline instead:
std::getline(std::cin, name);
For your purposes, you could probably do this, which is simpler:
std::string first, middle, last;
std::cin >> first >> middle >> last;