Combining Two Strings into One Variable in C++ - c++

I am en process of writing a simple program that assigns given student names into groups of whatever interval requested. Currently, I am focusing on the function that reads the name of the students.
Here is the code:
class student
{
public:
string nameFirst;
string nameLast;
};
student typeName()
{
student foo;
cout << "Type in a student's first name: ";
cin >> foo.nameFirst;
cout << "Type in that student's last name: ";
cin >> foo.nameLast;
cout << "\n";
return foo;
}
Since I cannot use getline(), I am forced to create two strings, one for each section of the student's full name. How can I rewrite this code to allow for it to take the full name without creating two variables and without using getline()? Or, if such isn't possible, how can I use a method within the class to combine the two strings into one?

You can just use
cin >> foo.nameFirst >> foo.nameLast;
cin >> will parse stops at white spaces, so you can just input the full name in one line split by space like James Bond.
To combine two strings into one:
string fullName = foo.nameFirst + " " + foo.nameLast;

Related

Program is not asking 3 questions and uses my answer to the first question for the other two

I am trying to ask the user to enter the names of 3 of their friends, however, it only asks one question and writes the answer from my first one in the second and third.
#include <iostream>
using namespace std;
int main()
{
char first_name;
cout << "Please enter a name: ";
cin >> first_name;
cout << first_name << endl;
char second_name;
cout << "Please enter a name: ";
cin >> second_name;
cout << second_name << endl;
char third_name;
cout << "Please enter a name: ";
cin >> third_name;
cout << third_name << endl;
return 0;
}
You should probably be using string in your code to take the input of names. In names you are probably passing more than one character. The first one is read by first_name and any further character will be read by the following character, specifically cin>>second_name and cin>>third_name would read the 2nd and 3rd character of your input.
char a;
char b;
cin>>a; //will only read one character and stop
cin>>b; //will read the second character of the input...
//be that after pressing enter(a Enter b) or continuous input (ab)
cout<<a<<" "<<b; //will output 1st and 2nd character only
This will happen even if you don't press the Enter key explicitly and this is why your program uses the answer of first question(which is probably more than 1 character since it is a name) in your code as the answer to 2nd and 3rd questions as well.
So for your purpose, you are better of using string to take input from the users.
Hope this clears your doubt !
You tried to hold a lot of chars (one word) in one char who can hold only one char.
#include <iostream>
#include <string> // We need a string, container to hold a chars. Something like array of chars but have a few difference.
using namespace std; // You should avoid using this but in that short code this doesn't matter
int main()
{
// You don't need separate container for this code
// Then we create one container to holds all of inputs
string input;
cout << "Please enter a name: ";
cin >> input; // Put input from user in our input(string)
cout << input << endl; // Print input
// Next code is the same as above
cout << "Please enter a name: ";
cin >> input;
cout << input << endl;
cout << "Please enter a name: ";
cin >> input;
cout << input << endl;
return 0;
}
I special avoided a few elements like using function because this must be simple as possible.

Confusion about cin function at run-time

int main()
{
cout<< "Please enter your first name (followed by 'enter'):\n";
string first_name; // first_name is a variable of type String
cin >> first_name; // read characters into first_name
cout<<"Hello, " <<first_name<<"!\n";
cout<<" first_name "<<" is "<< first_name <<"\n";
cout << "Please enter you first name and age\n";
string new_first_name = "unentered";
int age = -1;
cin >> new_first_name;
cin >> age;
cout << "Hello, " << new_first_name << "(age " << age << ") \n";
return 0;
}
I have the above bit of code that is basically an example from a book I've been working through.
Something rather funny happens when I compile and run that I didn't understand. On the first prompt, if I enter one name say 'Joe', then the rest of the program works fine. That is, I can enter a new name 'George" and age '23' at the second prompt and the output goes just fine.
If on the other hand, I enter two words separated by a comma in the first prompt, say 'Joe Person', then in the second prompt if I enter George 23, I get the output Person (age 0).
So it seems like it took the second name, used that in the second string prompt, and then did something with the age input. I'm surprised that it doesn't output the initialized value of -1.
Could anybody tell me what might be going on here? I would have thought that for the first prompt, the program would ignore whatever came after the first whitespace, but it appears as if it gets stored somehow and then get stored in the new_first_name variable.
The C++ stream extract operators, for strings, read tokens. That is anything up to the next peice of white-space.
Generally cpp-reference is a good reference for C/C++.
Use the getline function to take input in std::string datatype when the input can consist space.
So you can write: getline(cin,first_name);
And it will work fine.
If you use cin instead, it will just ignore the string input after first space occurred. For example, if you gave input 'Joe Person', cin will only store 'Joe' in the first_name Variable. It will also leave 'Person' as the next thing to be read.
You should use cin with std::string only when the input string does not contain space, if it consists space, then you should go for getline(), this function is implemented in std::string class for the same purpose.
Find the complete explanation here
It will work definitely.

Variable is getting assigned automatically

I was making a project that gets students' names, roll numbers & marks and returns percentage or grade according to need of user. I made a function using for loop to assign details(name, etc.) to variable but during change of for loop's argument, program was assigning ""(null) to the first variable in execution part. Am I missing any code here?
#include <iostream>
#include <stdio.h>
using namespace std;
class Data
{
public:
int Rno[3], phy[3], mat[3], chem[3];
char name[3][100];
void getInfo()
{
for(int i = 0; i < 3; i++)
{
cout << "Enter your name: ";
gets(name[i]);
cout << "Enter your Roll number: ";
cin >> Rno[i];
cout << "Enter your Physics marks: ";
cin >> phy[i];
cout << "Enter your Maths marks: ";
cin >> mat[i];
cout << "Enter your Chemistry marks: ";
cin >> chem[i];
}
};
};
int main()
{
Data d;
d.getInfo();
puts(d.name[1]);
}
First an explanation. Then some options to address the problem.
The problem is that you are mixing line-oriented input (gets()) with formatted input (cin >> ....) on the same input device/stream.
Such functions treat whitespace - particularly newlines - differently. And, because of that, you can get unexpected interactions. In this case, cin >> chem[i] will read an integral value, stop when it encounters a newline, leave the newline character waiting to be read. Then gets() - in the next iteration of the loop - will encounter the newline, and return immediately (hence the "null", to use your description).
OK; that's the explanation. What to do about it?
The solution is not to mix such styles of input. One option consistently use line oriented input to read EVERYTHING as a string, and then separately parse the string.
Some people will suggest approaches that involve discarding (or "flushing") the offending newlines. That approach doesn't work well if your input is complex (e.g. lots of different statements reading from the same stream in different ways) because it is necessary to ensure EVERY stray newline is discarded. It is also error-prone - you can unintentionally discard input your program needs to read.
Also avoid using gets() like the plague. It has been removed from recent C standards for a reason - it is inherently unsafe.
There are various ways using C++ streams (like cin) to safely read strings and other types. For example, if some_str is of type std::string, then std::getline(std::cin, some_str) can be used to read a complete line of input. std::getline() also has the advantage that it can read a string of arbitrary size. But, still, avoid using std::getline(cin, some_str) and streaming input (cin >> ...) on the same stream - because they STILL handle newlines differently.
Problem is with not flushing cout. In your case inside the loop cout must be flushed before calling gets .
cout << "Enter your name: "<<endl; // This cout should be flushed properly **with** new line character
gets(name[i]);
From #ProXicT comment
cout << "Enter your name: "<<flush; // This cout should be flushed properly **without** new line character
gets(name[i]);

Taking user input and plugging it into dynamically allocating array, Beginner C++

string firstname, lastname;
string phonenumber, email;
cout << "What is the first of the person that you would like to add? : ";
cin >> firstname;
cout << "What is the last of the person that you would like to add? : ";
cin >> lastname;
cout << firstname << " " << lastname << endl;
cout << "What is the phone number of that person? : ";
cin >> phonenumber;
I need help taking this user input and plugging it into an array. I honestly do not know how to do that, if I could get some help on that it would be great!
Create a struct named Record as follows
struct Record
{
string firstName, lastName,phone; //etc
};
If you know how many records you want to enter then you have to create an array of Record as follows
Record PersonInfo[5];
Now each index of PersonInfo let say PersonInfo[2] is a complete Record and you can access there fields like
PersonInfo[2].phone = "5655567" //etc
Now if you want to create array of Record but don't know the size then your best bet for now is to use a vector like follows. A vector is an array of changable size. You need to include the following header
#include<vector>
After wards you can do the following
vector<Record> PersonInfo //thats how vectors are declared
The name between <> bractes tell of what type you want a vector of ,you can write int as well.
Following is how you add items to a vector
Record r1,r2; // just for example
PersonInfo.push_back(r1);
PersonInfo. push_back(r2);
you may add any number of items in it and you can access them just like array as follows
PersonInfo[0] .lastName // its actually r1.lastName and so on
This may seem difficult for now you may want to learn vectors and their operations before going for dynamic memory allocation which requires that you understand what pointers are. I don't know that you know about pointers and how to use them that is why I reffered you vectors

cin skipping variables after entering name

I get an error when I try to run this. It lets me input the employee's name, and then once I press Enter it skips to the end, flying by hours and pay rate without letting me input them.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
string EmployeeName; //Employee Name
float EmployeeHours;
float EmployeePayRate; //Emplyee Hours, Employee PayRate
cout << setw(50) << "Employee Name: ";
cin >> EmployeeName;
cout << setw(50) << "EmployeeHours: ";
cin >> EmployeeHours;
cout << setw(50) << "EmployeePayRate: ";
cin >> EmployeePayRate;
system("PAUSE");
return 0;
}
I think the comment by #AleksandarStojadinovic provides the clue to your problem. Use
std::getline(std::cin, EmployeeName);
to read the name. Rest can be as they are.
I am having an error when I try to run this. It lets me input the
employees name, and then once you press enter it skips to the end.
flies by hours and pay rate without letting me input that.
Your name must be comprised of two/three names, maybe first middle and last or something like that. cin deals space separated string and enter separated string in the same way i.e it will take each space separated string as different input. And for that if your name has two names, the first one goes right but the second one goes to a variable which is declared as float and the program terminates abnormally. That's why using cin in this case isn't right at all.
You need to use another way to avoid that, like using getline(cin,EmployeeName) .