1 : http://itweb.fvtc.edu/ag/?u=3&f=cpp-assignment3
I am to swap the integer using a SwapInteger function outside the main function type using pointer. The user input a number and then the computer will compile and change the result to the given result that our professor have assigned.
I've tried creating a void swapInteger function and input some code in to see if that swap the code but that does nothing. So i just added some code into the main function but I don't think that's what our professor wanted us to do. He did stated "do not modify the main function"
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
// TODO: Implement the "SwapIntegers" function
void swapIntegers(int *first, int *second)
{
int *pSwapIntegers = first;
first = second;
second = pSwapIntegers;
}
// Do not modify the main function!
int main()
{
int first = 0;
int second = 0;
int *pFirst = new int (first);
int *pSecond = new int (second);
cout << "Enter the first integer: ";
cin >> first;
cout << "Enter the second integer: ";
cin >> second;
cout << "\nYou entered:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
swapIntegers(&first, &second);
cout << "\nAfter swapping:\n";
cout << "first: " << *pFirst << "\n";
cout << "second: " << *pSecond << "\n";
cout << "\nPress any key to quit.";
_getch();
return 0;
}
I expected the computer to compile the two integer that the user input and then show the swapped integer to the user. Please take a look at my code if you have questions
Inside of your swapIntegers(), you are swapping the pointers themselves, not the values of the variables they are pointing at. The caller's variables are not being updated.
swapIntegers() needs to look more like this instead:
void swapIntegers(int *first, int *second)
{
int saved = *first;
*first = *second;
*second = saved;
}
Also, your main() is buggy. It dynamically allocates 2 int variables that it leaks and never assigns the user's input values to. The final "After swapping" output is printing out values from those pointers, not from the variables that were actually swapped. The code will NOT display the expected output. So, despite what the instructions say, main() NEEDS to be modified in order to operate properly, and if your professor has a problem with that, tough. He made a mistake in the code he gave you.
main() should look more like this:
int main()
{
int first = 0;
int second = 0;
cout << "Enter the first integer: ";
cin >> first;
cout << "Enter the second integer: ";
cin >> second;
cout << "\nYou entered:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
swapIntegers(&first, &second);
cout << "\nAfter swapping:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
cout << "\nPress any key to quit.";
_getch();
return 0;
}
Or, like this:
// Do not modify the main function!
int main()
{
int first = 0;
int second = 0;
int *pFirst = &first;
int *pSecond = &second;
cout << "Enter the first integer: ";
cin >> first;
cout << "Enter the second integer: ";
cin >> second;
cout << "\nYou entered:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
swapIntegers(&first, &second);
cout << "\nAfter swapping:\n";
cout << "first: " << *pFirst << "\n";
cout << "second: " << *pSecond << "\n";
cout << "\nPress any key to quit.";
_getch();
return 0;
}
Or, like this:
int main()
{
int *pFirst = new int (0);
int *pSecond = new int (0);
cout << "Enter the first integer: ";
cin >> *pFirst;
cout << "Enter the second integer: ";
cin >> *pSecond;
cout << "\nYou entered:\n";
cout << "first: " << *pFirst << "\n";
cout << "second: " << *pSecond << "\n";
swapIntegers(pFirst, pSecond);
cout << "\nAfter swapping:\n";
cout << "first: " << *pFirst << "\n";
cout << "second: " << *pSecond << "\n";
delete pFirst;
delete pSecond;
cout << "\nPress any key to quit.";
_getch();
return 0;
}
UPDATE: oh wait, it is not your professor's fault, it is YOUR fault. The main() you have presented here DOES NOT match the main() given in the actual assignment!. This is what the original main() looks like:
// Do not modify the main function!
int main()
{
int first = 0;
int second = 0;
cout << "Enter the first integer: ";
cin >> first;
cout << "Enter the second integer: ";
cin >> second;
cout << "\nYou entered:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
SwapIntegers(&first, &second);
cout << "\nAfter swapping:\n";
cout << "first: " << first << "\n";
cout << "second: " << second << "\n";
cout << "\nPress any key to quit.";
_getch();
return 0;
}
This code is correct. So YOU are the one who introduced the bad use of pointers in main(). So just revert back to the original main() code you were given. And then implement swapIntegers() properly. As the instructions told you to do.
Related
The user is asked if s/he wants to return to main menu, if the user inputs n/N it only proceeds to the next solution when it should immediately end the program. Shown below is the code I used for the program. Please help me to make solution on how to end the program immediately when No is chosen as his/her choice. Thank you so much!
void number()
int b=0;
int groupChoice=0;
float ave[groupChoice];
int trials[groupChoice];
float result,sumRes,dAve;
int sumTry=0;
char choice;
cout << "\nNUMBER OF TRIALS" << endl;
cout << "\nHow many groups? ";
cin >> groupChoice;
for (int j=0;j<groupChoice;j++)
{
cout << "Average distance for group " << j+1 << ": ";
cin >> ave[j];
cout << "No. of trials for group " << j+1 << ": ";
cin >> trials[j];
}
cout << "\nGroups\t\tAve. Distance(x)\tNo. of trials(w)\tx(w)" << endl;
for (int i=0;i<groupChoice;i++)
{
result=ave[i]*trials[i];
cout << "Group " << i + 1 << "\t\t" << ave[i] << "\t\t\t" << trials[i] << "\t\t\t" << result << endl;
sumTry=sumTry+trials[i];
sumRes+=result;
}
cout << "\t\t\t\t\tSum = " << sumTry << "\t\tSum = " << sumRes << endl;
dAve = sumRes / sumTry;
cout << "Distance Average is " << dAve << endl << endl;
b=0;
while(b==0)
{
cout << "Would you like to return to main menu? [Y or N]: ";
cin >> choice;
if (choice=='Y'||choice=='y')
{
b++;
system("cls");
a=0;
main();
}
else if (choice=='N'||choice=='n')
{
b++;
break;
}
}
You can terminate your program with
void std::exit( int exit_code );
eg
std::exit(EXIT_SUCCESS);
https://en.cppreference.com/w/cpp/utility/program/exit
There are two options
use
std::exit(<exit_code>); or
std::_Exit(<exit_code>);
more info:
https://en.cppreference.com/w/c/program/_Exit
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct football_game
{
string visit_team;
int home_score;
int visit_score;
};
void printMenu();
int main()
{
int i, totalValues = 0;
ifstream inputFile;
string temp = "";
inputFile.open("games.txt");
if (!inputFile)
{
cout << "Error opening Input file!" << endl;
exit(101);
}
inputFile >> totalValues;
getline(inputFile, temp);
cout << " *** Football Game Scores *** " << endl << endl;
cout << " * Total Number of teams : " << totalValues << endl << endl;
football_game* records = new football_game[totalValues];
// while (!inputFile.eof())
// {// == NULL) {
for (i = 0; i < totalValues; i++)
{
getline(inputFile, records[i].visit_team);
cout << records[i].visit_team << endl;
inputFile >> records[i].home_score >> records[i].visit_score;
cout << records[i].home_score << " " << records[i].visit_score << endl;
getline(inputFile, temp);
}
//}
cout << endl;
int choice = 0;
int avg_home_Score = 0;
int avg_visit_Score = 0;
printMenu(); // prints menu
cout << "Please Enter a choice from the Menu : ";
cin >> choice;
cout << endl << endl;
while (true)
{
switch (choice)
{
case 1:
cout << " Score Table " << endl;
cout << " ***********************" << endl << endl;
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
for (int i = 0; i < totalValues; i++)
{
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|' << setw(7)
<< right << records[i].visit_score << " " << '|' << endl;
}
cout << endl << endl << endl;
break;
case 2:
{
string team_name;
cout << "Enter the Team Name : ";
cin >> team_name;
for (int i = 0; i < totalValues; i++)
{
if (records[i].visit_team == team_name)
{
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|'
<< setw(7) << right << records[i].visit_score << " " << '|'
<< endl;
}
}
cout << endl;
break;
}
case 3:
{
for (int i = 0; i < totalValues; i++)
avg_home_Score += records[i].home_score;
cout << "Average home_score: " << (avg_home_Score / totalValues) << endl << endl;
break;
}
case 4:
{
for (int i = 0; i < totalValues; i++)
avg_visit_Score += records[i].visit_score;
cout << "Average visit_score: " << (avg_visit_Score / totalValues) << endl << endl;
break;
}
default:
{
cout << "Please enter valid input !!" << endl;
break;
}
}
printMenu();
cin >> choice;
}
return 0;
}
void printMenu()
{
cout << " Menu Options " << endl;
cout << " ================ " << endl;
cout << " 1. Print Information of all Games[Table Form] " << endl;
cout << " 2. Print Information of a Specific Game " << endl;
cout << " 3. Print Average points scored by the Home Team during season" << endl;
cout << " 4. Print Average points scored against the Home Team" << endl << endl << endl;
}
Here is the input file i am using
games.txt
5
SD Mines
21 17
Northern State
10 3
BYU
10 21
Creighton
14 7
Sam Houston State
14 24
When i am using the 2nd option (Print Information of a Specific Game) from the output screen,
it ask me to enter the team name and when i enter the team-name.
For example: SD Mines it gives me an error, but when I enter the team-name with no space like: BYU it works fine for me.
cin >> team_name;
Takes the input only upto space.
You might want to use cin.getline() for taking space separated strings as input.
A small program demonstrating the same :
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Name is : , " << name << "!\n";
return 0;
}
std::cin ignores whitespaces by default.
To include spaces in your input try :
getline(cin, team_name);
This would pick up all the characters in a line until you press enter. This is available in
#include<string>
You need to flush the std::cin buffer after reading the choice:
#include <limits>
//...
cin >> choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Refer to this question for detailed explanation.
Also, if you want to read strings with spaces from the standard input, replace this:
cin >> team_name;
with this:
getline(cin, team_name);
as already mentioned in other answers. No need to flush std::cin this time, since you have already read the full line.
Finally, remove extra newlines from your games.txt:
5
SD Mines
21 17
Northern State
...
I'm working on an assignment in my first semester of C++ and I just can't figure out working syntax for it. I need to pass a struct as a parameter to a class function using a pointer. This code I've copied is my best attempt, and it will compile but it crashes when it asks for the first name. When I try variations in the syntax, I get errors about incomplete struct, undefined variables (warrior was or invalid operators. What am I doing wrong?
#include <iostream>
using namespace std;
class StarWars
{
public:
int totalNumber;
struct data_clone
{
int ID, timeCounter;
string name;
};
data_clone *warrior;
void createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
}
void input(struct data_clone *pointer, int total)
{
for(int i = 1; i <= total; i++)
{
cout << "For warrior number " << i << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> pointer[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> pointer[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> pointer[i].timeCounter;
}
}
void lifeSpan(struct data_clone *pointer, int total)
{
for(int i = 1; i <= total; i++)
{
cout << "Warrior number " << pointer[i].name << ": " << endl;
while(pointer[i].timeCounter > 0)
{
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is alive." << endl;
pointer[i].timeCounter--;
}
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}
};
int main(void)
{
StarWars clones;
clones.createClone();
clones.input(clones.warrior, clones.totalNumber);
clones.lifeSpan(clones.warrior, clones.totalNumber);
}
You don't initialise the memory warrior points to, so you're working with uninitiailised memory - always a bad thing. There's two things to keep in mind here:
When working with pointers, always initialise the memory behind them first. Prefer using RAII concepts like std::unique_ptr / std::shared_ptr
void DoStuff(Widget* w);
std::unique_ptr<Widget> pw = std::make_unique<Widget>();
DoStuff(w.get());
When working with normal variables, use the dereference / reference operators to take a pointer to the variable.
void DoStuff(Widget* w);
Widget widget;
DoStuff(&w);
struct data_clone
{
int ID, timeCounter;
string name;
};
class StarWars
{
private:
data_clone *warrior;
int totalNumber;
public:
StarWars()
{
}
~StarWars()
{
delete[] warrior; // clean up
}
void createClone();
void input();
void lifeSpan();
};
void StarWars::createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
// construct structure baased on input
warrior = new data_clone[totalNumber];
}
void StarWars::input()
{
for(int i = 0; i < totalNumber; i++)
{
cout << "For warrior number " << i+1 << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> warrior[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> warrior[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> warrior[i].timeCounter;
}
}
void StarWars::lifeSpan()
{
std::cout<<"**********Print data**********\n";
for(int i = 0; i < totalNumber; i++)
{
cout << "Warrior number " << warrior[i].name << ": " << endl;
while(warrior[i].timeCounter > 0)
{
cout << "Warrior name: " << warrior[i].name << endl;
cout << "Warrior ID number: " << warrior[i].ID << endl;
cout << "Warrior time counter: " << warrior[i].timeCounter << endl;
cout << "Clone is alive." << endl;
warrior[i].timeCounter--;
}
cout << "Warrior name: " << warrior[i].name << endl;
cout << "Warrior ID number: " << warrior[i].ID << endl;
cout << "Warrior time counter: " << warrior[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
StarWars clones;
clones.createClone();
clones.input();
clones.lifeSpan();
return 0;
}
You never created your clones, you only read how many there should be.
Allocate space for them:
void createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
warrior = new data_clone[totalNumber];
}
Your array indexes are also off - an array of size N is indexed from 0 to N - 1.
But the more common way of handling this is to pass the amount to the constructor and let the object handle its own members:
class StarWars
{
public:
StarWars(int clones)
: totalNumber(clones),
warrior(new data_clone[clones])
{
}
void input()
{
for(int i = 0; i < totalNumber; i++)
{
cout << "For warrior number " << i << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> warrior[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> warrior[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> warrior[i].timeCounter;
}
}
void lifeSpan()
{
for(int i = 0; i < totalNumber; i++)
{
cout << "Warrior number " << i << ": " << endl;
while(warrior[i].timeCounter > 0)
{
cout << "Warrior name: " << warrior[i].name << endl;
cout << "Warrior ID number: " << warrior[i].ID << endl;
cout << "Warrior time counter: " << warrior[i].timeCounter << endl;
cout << "Clone is alive." << endl;
warrior[i].timeCounter--;
}
cout << "Warrior name: " << warrior[i].name << endl;
cout << "Warrior ID number: " << warrior[i].ID << endl;
cout << "Warrior time counter: " << warrior[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}
private:
int totalNumber;
struct data_clone
{
int ID, timeCounter;
string name;
};
data_clone *warrior;
};
int main()
{
int number = 0;
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> number;
StarWars clones(number);
clones.input();
clones.lifeSpan();
}
Note that you need to handle the destructor, the copy constructor, and the assignment operator properly as well (left as an exercise).
class StarWars
{
private:
struct data_clone
{
int ID, timeCounter;
string name;
};
public:
StarWars()
{
warrior = new data_clone[4];
}
~StarWars()
{
delete[] warrior;
}
int totalNumber;
data_clone *warrior;
void createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
}
void input(struct data_clone *pointer, int total)
{
for(int i = 0; i < total; i++)
{
cout << "For warrior number " << i << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> pointer[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> pointer[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> pointer[i].timeCounter;
}
}
void lifeSpan(struct data_clone *pointer, int total)
{
for(int i = 0; i < total; i++)
{
cout << "Warrior number " << pointer[i].name << ": " << endl;
while(pointer[i].timeCounter > 0)
{
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is alive." << endl;
pointer[i].timeCounter--;
}
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}
};
Note: I just hardcoded it which is not the correct way, it force you to enter only 4 tyeps of dataclone
"warrior = new data_clone[4];"
you will at least get your result
I want to print the data using pointers i've done it using for but not getting how to use pointer in array of structures so is there any one who can help me and get me out of it....
#include <iostream>
#include <cstdio>
#include <conio.h>
using namespace std;
int main()
{
struct employee
{
char e_name[20];
int e_id;
int e_age;
char e_degree[20];
};
struct employee e[3];
int i = 1;
cout << "Enter the Employee Data:" << endl;
for (i=1; i<4; i++)
{
cout << "Data of Employee #" << i << ":" << endl;
cout << "Enter Employee Name:" << endl;
cin >> e[i].e_name;
cout << "Enter Employee ID:" << endl;
cin >> e[i].e_id;
cout << "Enter Employee age:" << endl;
cin >> e[i].e_age;
cout << "Enter Employee Highest Degree (Graduation/Masters/Mphil/):" << endl;
cin >> e[i].e_degree;
}
struct employee *ptr;
ptr = &e[3];
for (i=1; i<4; i++)
{
cout << e[i].e_name, e[i].e_id, e[i].e_age, e[i].e_degree;
cout << "Data of Employee #" << i << ":" << endl;
cout << "Name: " << ptr->e_name << endl;
cout << "ID: " << ptr->e_id << endl;
cout << "Age: " << ptr->e_age << endl;
cout << "Degree: " << ptr->e_degree << endl;
}
getch();
return 0;
}
Your pointer is pointing to the third element of an array. Having that in mind, your for loop will print out the third element three times. You should pass your array identifier e(also a pointer) to "ptr", and then increment "ptr" in for loop. That's called pointer arithmetic.
More info: http://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htm
Also, since C++ is OO language, i would recommend using classes instead of structures.
Arrays start with index of 0, not 1. Pointer to the end is not helpful either, you want to point to the beginning of the array and increment each iteration through your print loop.
#include <iostream>
#include <cstdio>
#include <conio.h>
using namespace std;
int main()
{
struct employee
{
char e_name[20];
int e_id;
int e_age;
char e_degree[20];
};
struct employee e[3];
int i = 0;
cout << "Enter the Employee Data:" << endl;
for (i=0; i<3; ++i)
{
cout << "Data of Employee #" << (1+i) << ":" << endl;
cout << "Enter Employee Name:" << endl;
cin >> e[i].e_name;
cout << "Enter Employee ID:" << endl;
cin >> e[i].e_id;
cout << "Enter Employee age:" << endl;
cin >> e[i].e_age;
cout << "Enter Employee Highest Degree (Graduation/Masters/Mphil/):" << endl;
cin >> e[i].e_degree;
}
struct employee *ptr = e;
for (i=0; i<3; ++i, ++ptr)
{
cout << e[i].e_name, e[i].e_id, e[i].e_age, e[i].e_degree;
cout << "Data of Employee #" << (1+i) << ":" << endl;
cout << "Name: " << ptr->e_name << endl;
cout << "ID: " << ptr->e_id << endl;
cout << "Age: " << ptr->e_age << endl;
cout << "Degree: " << ptr->e_degree << endl;
}
getch();
return 0;
}
struct employee *ptr;
ptr = &e[3];
for (i=1; i<4; i++)
{
cout << e[i].e_name, e[i].e_id, e[i].e_age, e[i].e_degree;
cout << "Data of Employee #" << i << ":" << endl;
cout << "Name: " << ptr->e_name << endl;
cout << "ID: " << ptr->e_id << endl;
cout << "Age: " << ptr->e_age << endl;
cout << "Degree: " << ptr->e_degree << endl;
}
This code, probably, doesn't do what you expect. It's because ptr always points to the same thing (e[3]).
replace it with:
struct employee *ptr;
for (i=1; i<4; i++)
{
ptr = &e[i-1]; //i-1 because 0 is actually the first element
.... //your code
}
You can do the same thing by setting pointer to the first element of your array, and increase it in your loop.
Okay so as the title said its refusing to execute the stuff right under the "do" function even though as far as i can tell all the parameters for a repeat have been fulfilled. So far what i get when i run the program is something along the lines of...
"Would you like to search another name?
Please enter Y for yes and n for no:"
looping over and over when i press y
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main()
{
vector <string> vName, vID, vClass;
string sName, sID, sClass, sSearch, cQuestion;
int iSize, iStudent;
// Display initial vector size
iSize = vName.size();
cout << "Student list starts with the size:" << iSize << endl;
// Get size of list from user
cout << "How many students would you like to add?" << endl;
cin >> iStudent;
cin.ignore();
// Get names, ids, and classes
for (int i = 0; i < iStudent; i++)
{
cout << "Student" << i + 1 << ":\n";
cout << "Please enter the student name: ";
getline(cin, sName);
vName.push_back(sName);
cout << "Enter ID number ";
getline(cin, sID);
vID.push_back(sID);
cout << "Enter class name ";
getline(cin, sClass);
vClass.push_back(sClass);
}
// Display header
cout << "The list of students has the size of: " << iStudent << endl;
cout << "The Student List" << endl;
cout << "\n";
cout << "Name:" << setw(30) << "ID:" << setw(38) << "Enrolled Class : " << endl;
cout << "--------------------------------------------------------------------------";
cout << "\n";
// for loop for displying list
for (int x = 0; x < vName.size() && vID.size() && vClass.size(); x++)
{
cout << vName[x] << "\t \t \t" << vID[x] << "\t \t \t" << vClass[x] << endl;
}
// Sorting function
cout << "\n";
cout << "The Student List after Sorting:" << endl;
cout << "\n";
sort(vName.begin(), vName.end());
for (int y = 0; y < vName.size(); y++)
{
cout << vName[y] << endl;
}
cout << "\n";
// Search function
do
{
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
} while (cQuestion == "Y" || cQuestion == "y");
cout << "Thank you for using this program!" << endl;
return 0;
}
Edit:
Posted whole program, please excuse any grammatical mistakes, I'm just trying to get the program down before i go in there and make it pretty.
The tail of your loop does this:
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
which will consume your string if you entered one, but leave the trailing newline in the input stream. Thus when you return to the top of the loop after entering Y or y, and do this:
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
the getline will extract an empty line.
How to consume the unread newline from the input stream is up to you. You will likely just end up using .ignore() as you did prior in your program. Or use getline to consume cQuestion. You have options. Pick one that works.
And as a side note, I would strongly advise you check your stream operations for success before assuming they "just worked". That is a hard, but necessary, habit to break. Something like this:
do
{
cout << "Please Enter a name to be searched:" << endl;
if (!getline(cin, sSearch))
break;
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
} while (getline(cin,cQuestion) && (cQuestion == "Y" || cQuestion == "y"));
If cQuestion is a char array then you need to use strcmp or stricmp to compare it with another string i.e. "Y" and "y" in this case. If cQuestion is a single char then you need to compare with 'Y' and 'y' (i.e. with a single quote)
Strings in C++ are not first class types therefore they do not have some of the string operation that exist for other basic types like ints and floats. You do have std::string as part of the standard C++ library which almost fulfills the void.
If you just change the type of cQuestion to std::string your code should work but if you want to stick with chars then you will need to change the quote style.