Below I am setting up a y/n question in the program, I know I need an identifier named i for the cin line to work in the if's. However, I'm not sure where to put my identifier.
#include <iostream>
#include <string>
using std::string, std::cin, std::cout, std::endl;
int main() {
const int MaxNum = 3;
int simcard;
string familyone[MaxNum] = {
"Name One",
"Name Two",
"Name Three"
};
int famnumone[MaxNum];
int choice;
string familytwo[MaxNum] = {
"Name One",
"Name Two",
"Name Three"
};
int famnumtwo[MaxNum];
string familythree[MaxNum] = {
"Name One",
"Name Two",
"Name Three"
};
int famnumthree[MaxNum];
string phonetype[MaxNum] = {
"Iphone",
"Android",
"Random Phone"
};
string familysim[MaxNum] = {
"Family one Sim",
"Family two Sim",
"Family Three Sim"
};
string simtype[MaxNum] = {
"Iphone SIM",
"Android SIM",
"Random Phone SIM"
};
//Here we have information for each family members name to later identify who each phone belongs too
cout << "SIM card matching tool\n";
cout << "Enter Family One Names ==>";
for (int i = 0; i < MaxNum; i++) {
getline(cin, familyone[i]);
}
do {
cout << "would you like to continue to the sim/y, or would you like to add another family/n" << endl;
cin >> choice;
choice = tolower(choice);
} while (choice != 'n' && choice != 'y');
if (choice == 'n') {
cin >> familytwo[i];
if (choice == 'y')
cin >> simtype[i];
}
//add y/n below or possibly add a more complex anwser "if you would like to continue with the SIM type SIM or if you would like to add another family type family
cout << "Would you like to continue to the SIM/y, or would you like to add another family/n";
}
I think you messesd up your do-while loop:
i=0;
do {
cout << "would you like to continue to the sim/y, or would you like to add another family/n" << endl;
cin >> choice;
choice = tolower(choice);
if (choice == 'n')
cin >> familytwo[i];
if (choice == 'y')
cin >> simtype[i];
i++;
} while (choice != 'n' && choice != 'y')
EDIT: you can increment i in every round.
Related
need to limit the ammount of items that can be entered into the array to 5. Tought i would use a do while loop but it just continues even after the 5 items have been entered. Any help would be appreciated
#include "stdafx.h"
#include <string>
#include <conio.h>
#include <iostream>
#include <array>
using namespace std;
string sItems[4] = {};
string sChoice = "";
int iItemPrice[4] = {};
int iNumOfItems = 0;
int iMenuChoice = 0;
int iCount = 0;
int main()
{
cout << "--------- Welcome to the program ---------\n\n Please pick from an option below: \n 1: Enter new items \n 2: Change item prices \n 3: Input sold items \n 4: Receipt for previous items sold\n ";
cin >> iMenuChoice;
switch (iMenuChoice)
{
case 1:
{
do {
cout << "--------- ENTER NEW ITEMS ---------\n\nPlease enter the item Name: ";
cin >> sItems[iCount];
cout << "\nPlease enter the price of: " << sItems[iCount] << "\n";
cin >> iItemPrice[iCount];
cout << "\nWould you like to enter another item? Y/N \n";
cin >> sChoice;
if (sChoice == "Y" || sChoice == "y")
{
++iCount;
++iNumOfItems;
}
} while (sChoice == "Y" || sChoice == "y" || iNumOfItems < 5);
cout << "you have entered the maximum ammount of items";
}
}
_getch();
return 0;
}
The loop condition sChoice == "Y" || sChoice == "y" || iNumOfItems < 5 means:
Loop as long as user answers "Y"
But at least 5 times regardless of user answer
If you want some other logic, like loop up to 5 times, then you can reflect that in the code.
Also check for failures. If you input a character when cin expects a number, it will enter a failed state and all subsequent input attempts will fail.
do {
cout << "--------- ENTER NEW ITEMS ---------\n\nPlease enter the item Name: ";
cin >> sItems[iCount];
cout << "\nPlease enter the price of: " << sItems[iCount] << "\n";
if (!(cin >> iItemPrice[iCount]))
break;
cout << "\nWould you like to enter another item? Y/N \n";
cin >> sChoice;
++iCount;
++iNumOfItems;
} while ((sChoice == "Y" || sChoice == "y") && iNumOfItems < 5);
And increase the array size from 4 to 5 if you want to support 5 items:
string sItems[5];
int iItemPrice[5];
How to fix the code? I can't use vectors. I need to be able to call the names for the courses from the first while to the second one and display them.
cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
while (count <= nclass ) // while
{
//Information for the class
{
cout << "Please enter the course name for the class # "<< count << endl;
getline (cin, name);
string name;
string coursename[nclass];
for (int i = 0; i < nclass; i++) {
coursename[i] = name;
}
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
for (int x = 0; x < nclass; x++){
cout << "Here is a list of all the courses: \n" << coursename[i] << endl;
}
return 0 ;
}
you are declaring coursename as local inside loop and then using it outside so you get a compile time error (coursename is undeclared identifier).
one question: what is the role of inner for-loop????!!!
you use a for loop inside while loop through which you are assigning all the elements the same value as the string name has!!!
so every time count increments the inner for loop assigns the new value of name after being assigned, to the all elements of coursename.
count is undefined! so declare it and initialize it to 1 or 0 and take this in mind.
you wrote to the outbounds of coursname: count <= nclss to correct it:
while(count < nclass)...
another important thing: clear the input buffer to make cin ready for the next input. with cin.ignore or sin.sync
cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
string coursename[nclass];
int count = 0;
while (count < nclass ) // while
{
//Information for the class
string name;
cout << "Please enter the course name for the class # "<< count << endl;
cin.ignore(1, '\n');
getline (cin, name);
coursename[count] = name;
cin.ignore(1, '\n');
count++;
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
for (int x = 0; x < nclass; x++){
cout << "Here is a list of all the courses: \n" << coursename[x] << endl;
}
This code works!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nclass = 0, count = 1, countn = 1;
string name[100];
cout << "Please enter the number of classes" << endl;
cin >> nclass;
while (count <= nclass) {
cout << "Please enter the course name for the class # " << count << endl;
cin >> name[count];
count++;
}
cout << "Here is a list of all the courses: " << endl;
while (countn <= nclass) {
cout << name[countn] << endl;
countn++;
}
return 0;
}
Note that gave the array "name" the size of 100. Nobody is going to have 100 classes! There is no need for the for loops. It is a good practice to initialize the count and the new count which is designated by countn. Why is my answer voted down when it works?
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <iomanip>
using namespace std;
int main()
{
char response = 'y';
while (response == 'y')
do
{
const int numberofnames = 200;
vector <string> boynamevector(numberofnames);
vector <string> girlnamevector(numberofnames);
ifstream readboy;
ifstream readgirl;
string boy;
string girl;
int choice;
readboy.open("BoyNames.txt");
readgirl.open("GirlNames.txt");
bool check = true;
int boychoice = 1;
int girlchoice = 2;
int bothchoice = 3;
for (int counter = 0; counter < numberofnames; counter++)
{
readboy >> boynamevector[counter];
readgirl >> girlnamevector[counter];
}
cout << "\t\Popular Boy or Girl or Both Choices\n\n"
<< "1. Popular Boy Name\n"
<< "2. Popular Girl Name\n"
<< "3. Popular name for both Boy and Girl\n"
<< "Enter choice: ";
cin >> choice;
if (choice == boychoice)
cout << "Enter a boy's name: ";
cin >> boy;
check = false;
int counter;
for (counter = 0; counter < numberofnames; counter++);
{
if (boy == boynamevector[counter])
check = true;
}
if (check == true)
cout << "The name is popular\n";
else
cout << "The name is not popular\n";
cout << "Would you like to run the program again? \n"
<< "Enter y for yes or n for no: ";
cin >> response;
} while (response == 'Y' || response == 'y');
return 0;
}
I think the problem is in the first for loop that appears. I'm not sure that the names are being transferred from the open file to the string array/vector and I'm not entirely sure how to make that work. If anyone could help or give some suggestions that would be greatly appreciated.
You have a typo:
for (counter = 0; counter < numberofnames; counter++);
That semicolon makes the next lines be a normal block, so boynamevector[counter] is out of range.
First you need properly read all the boys and girls names BEFORE you enter the loop so you don't re-read the names over and over again:
string response = "y";
ifstream readboy;
ifstream readgirl;
//Open the files
readboy.open("BoyNames.txt");
readgirl.open("GirlNames.txt");
if(!readboy.is_open())
return 0;
if(!readgirl.is_open())
return 0;
vector <string> boynamevector;
vector <string> girlnamevector;
string szName;
while(getline(readboy, szName))
boynamevector.push_back(szName);
while(getline(readgirl, szName))
girlnamevector.push_back(szName);
readboy.close();
readgirl.close();
Then iterate over and over comparing the strings
do
{
string boy;
string girl;
int choice;
bool bExists = true;
int boychoice = 1;
int girlchoice = 2;
int bothchoice = 3;
cout << "\tPopular Boy or Girl or Both Choices\n\n"
<< "1. Popular Boy Name\n"
<< "2. Popular Girl Name\n"
<< "3. Popular name for both Boy and Girl\n"
<< "4. Exit\n"
<< "Enter choice: ";
cin >> choice;
if(choice == 4)
break;
if (choice == boychoice)
cout << "Enter a boy's name: ";
if (choice == girlchoice)
cout << "Enter a girls's name: ";
cin >> boy;
bExists = false;
//Find the name
if(choice == 3 || choice == 1)
{
for (unsigned int i = 0; i < boy.size(); i++)
{
if (boy == boynamevector[i])
bExists = true;
}
}
else if(choice == 3 || choice == 1)
{
for (unsigned int i = 0; i < girlnamevector.size(); i++)
{
if (boy == girlnamevector[i])
bExists = true;
}
}
if (bExists == true)
cout << "The name is popular\n";
else
cout << "The name is not popular\n";
cout << "Would you like to run the program again? \n"
<< "Enter y for yes or n for no: ";
cin >> response;
} while (response == "Y" || response == "y");
return 0;
Alright, I been trying to do this for a couple of hours but I'm not getting anywhere. First of
all, I have 2 text files that I need to read from a different function which is simple enough. Then for one of the text files, mainly the college.txt, I have to add it to a vector of strings; for the other text file(states.txt), I have to add the states to parallel arrays of strings.
The problem(This is related to the college.txt file) I have is how do I compare the strings the user inputs to the strings inside the vector since I have to validate whether or not the colleges/universities that the user inputs are on the list(and of course repeat it until the user decides to quit but that's also simple enough to do with a while loop).
Note1: Before you ask, The else/if with empty statements are empty because I want to focus on this problem first and then I will continue on with the program.
Note2: The IDE that I'm using is CodeBlocks
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
using namespace std;
bool DoesStringEqualVector(vector<string> total, string name)
{
for (unsigned int i=0; i < total.size(); ++i)
{
if (name == total[i])
return true;
}
return false;
}
void collegesUniversities(string)
{
ifstream campuses;
campuses.open("colleges.txt");
string schools;
vector<string> schoolVector;
if(!campuses)
cerr << "Error opening file. ";
else
{
while(campuses.good())
{
getline(campuses,schools, '\n');
schoolVector.push_back(schools);
cout << schools << endl;
}
}
DoesStringEqualVector(schoolVector, schools);
campuses.close();
}
int main()
{
char response;
string comparison;
int choice;
string userInput;
cout << "\nWelcome to my college and university search program.\n";
cout << "\nPress any button to continue.\n ";
system("pause>nul");
do
{
cout << "\nPress 1 to enter possible colleges and universities.";
cout << "\nPress 2 to find out how many colleges and universities";
cout << " appear in your state.\n";
cout << "Press 3 to find the total amount of colleges and";
cout << " universities in our list. ";
cout << "\nPress 4 to quit. ";
cin >> choice;
if(choice == 1)
{
do
{
cout << "\nEnter the name of your college/university. ";
cin >> userInput;
collegesUniversities(comparison);
if(userInput != comparison)
cout << "\nThis institution isn't on out list.\n ";
else
cout << "\nThis institution is on the list.\n";
cout << "\nWould you like to return to the menu?[Y/N] ";
cin >> response;
while(response != 'Y' && response != 'y' && response != 'N' &&
response != 'n')
{
cerr << "\nError, Invalid Input.";
cin >> response;
}
}
while(response != 'N' && response != 'n');
}
else if(choice == 2)
{
}
else if(choice == 3)
{
}
else if(choice == 4)
{
cout << "\nThank you for using my program. ";
cout << "Have a great day.\n ";
}
else
{
cerr << "\nError, Invalid input. ";
cout << "Only integers from 1 through 4 are allowed.\n";
}
}
while(choice != 4);
}
Wrap it all up in a method that checks through the vector:
bool IsStringInVector(vector <string> collection, string item)
{
for (int i=0; i < collection.size(); ++i)
{
if (item == collection[i])
return true;
}
return false;
}
You have to scan through the collection to see if it's in there.
How can I read input line(type string) with whitespace? I tried getline but it goes into infinite loop. Following is my code.
#include <iostream>
#include <cstring>
#define MAX 50 //size of array
//Used G++ 4.6.3 compiler
using namespace std;
int main() {
struct Manager {
string name;
int age;
int working_years;
string phone;
int salary;
}info[MAX];
char inp; //To choose options
int array_pos = 0; //Current position in array of Manager structure
string search_name; //Manager name you want to search
cout << "Press 'i' to insert manager information or 's' to search for manager information by name or 'a' to abort: ";
cin >> inp;
while(inp != 'a') {
int search_num = 0; //array position at which search result is found
int found = 0;
if (inp == 'i' || inp == 's') {
if (inp == 'i') {
int k = array_pos;
cout << "Enter the information of the manager no "<<k+1<<" is : ";
cout << "Enter the Name : ";
//infinte loop occurs
getline(info[array_pos].name, '\n');
//cin >> info[array_pos].name;
cout<<"Enter manager age : ";
cin >> info[array_pos].age;
cout << "Enter manage working years : ";
cin >> info[array_pos].working_years;
cout << "Enter manager phone no. : ";
cin >> info[array_pos].phone;
cout << "Enter manager salary : ";
cin >> info[array_pos].salary;
array_pos++;
}
if (inp == 's') {
cout << "Enter the manager name you want to search : ";
cin >> search_name;
for(int i = 0; i < array_pos; i++) {
//using str1.compare(str2) to compare manager name
if(info[i].name.compare(search_name) == 0) { //manager name found in array of structure
found = 1;
search_num = i;
cout << "Name : " << info[search_num].name << "\n";
cout << "Age: " << info[search_num].age << "\n";
cout << "Working Years: " << info[search_num].working_years << "\n";
cout << "Phone No. : " << info[search_num].phone << "\n";
cout << "Salary : " << info[search_num].salary << "\n";
} //end of if loop for comparing string
} //end of for loop for searching
if(found == 0)
cout << "No Manager by this name exist in record" << "\n";
} //end of if loop
} //end of if loop for searching or insertion
if(inp == 'a')
break;
cout << "Press 'i' to insert manager information or 's' to search for manager information by name or 'a' to abort: ";
cin >> inp;
} //end of while loop
return 0;
}
How can I read input line(type string) with whitespace?
std::string line;
if (std::getline(std::cin, line)) {
...
}
Note that apart from checking the return value of std:getline call, you should also avoid mixing >> operator with std::getline calls. Once you decide reading the file line by line, it seems to be cleaner and more reasonable to just make one huge loop and do the additional parsing while using string stream object, e.g.:
std::string line;
while (std::getline(std::cin, line)) {
if (line.empty()) continue;
std::istringstream is(line);
if (is >> ...) {
...
}
...
}
Simplest way to read string with spaces without bothering about std namespace is as follows
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
getline(cin,str);
cout<<str;
return 0;
}
Solution #1:
char c;
cin >> noskipws; // Stops all further whitespace skipping
while (cin >> c) { // Reads whitespace chars now.
count++;
}
Solution #2:
char c;
while (cin.get(c)) { // Always reads whitespace chars.
count++;
}