I have the following code below:
int main ()
{
char string[80];
bool Restart;
Restart = true;
while (Restart)
{
cout << "Enter a string\n" << endl;
cin.getline(string, 80);
cout << "\nYou entered: ";
printf(string, 80);
cout << endl;
int len=strlen(string);
bool flag = true;
for (int c=0; c!=len/2; c++)
{
if (flag)
{
if(string[c] != string[len-c-1])
{
flag = false;
}
}
else
{
break;
}
}
if (flag)
{
cout <<"\nThis is a Palindrome\n" << endl;
Restart = true;
continue;
}
else
{
cout << "\nThis is not a palindrome\n" << endl;
Restart = true;
continue;
}
cin.get();
}
}
I need to figure out a way to check if what the user entered is "END" in all caps, and if so, exit the program. I'm sure i can handle the exiting part, but I'm having trouble getting something that will check if the string entered is "END" in all caps.
Here is a solution that will terminate the while loop if "END" is entered. Create a helper method to do the parsing for END. Note this is very specific to the problem and not very reusable. It also is more difficult to maintain unlike Beta's solution, but you don't need to worry about maintenance until you start writing bigger programs.
bool Terminate(char* string, int len)
{
bool retval = false;
char* c = string;
if( 3 == len ) // "END\0"
{
if('E' == string[0])
{
if('N' == string [1])
{
if('D' == string[2])
{
retval = true;
}
}
}
}
return retval;
}
Then use it after int len=strlen(string); like so:
if(Terminate(string, len))
{
break; // Exit while loop
}
Make sure you declare Terminate before your main function
Is this enough of a hint?
#include <iostream>
int main()
{
char A[] = "END";
char B[10];
std::cin >> B;
std::cout << strcmp(A,B) << std::endl;
return(0);
}
Related
I am very new to C++ and am trying to complete an assignment involving loops. The goal of the activity is to print "valid" for passwords not containing the character "S" and "invalid" for those that do.
Here's the code:
#include <iostream>
using namespace std;
int main() {
bool validPassword;
string codeWord;
int passLength;
cin >> codeWord;
passLength = codeword.length();
for (int i = 0; i <= passLength; ++i) {
if (codeWord.at(i) != 'S') {
validPassword = true;
continue;
}
else {
validPassword = false;
break;
}
}
if (validPassword) {
cout << "Valid" << endl;
}
else {
cout << "Invalid" << endl;
}
return 0;
}
I'm kinda new to c++ as well, but this code I made worked for it. I used 'codeWord.find()' instead of cycling through all of the characters in the string. Here is the code:
#include <iostream>
using namespace std;
int main() {
bool validPassword;
string codeWord;
cin >> codeWord;
if(codeWord.find("8") == string::npos) {
validPassword = true;
}
else{
validPassword = false;
}
if (validPassword) {
cout << "Valid" << endl;
}
else {
cout << "Invalid" << endl;
}
return 0;
}
I'm working through a text book for self study. I can do the while loop no problem, but I have no idea how to do the terminating character.
Here is what I have now:
#include "../../std_lib_facilities.h" // Supplied by book author
int main()
{
int ii = 0;
int yy = 0;
bool test = true;
cout << "Enter two ints" << endl;
while (test)
{
cin>>ii, cin>>yy;
// this if statement doesn't work
if (ii == '|' || yy == '|')
{
test = false;
}
// this if statement catches all bad input, even the terminating '|'
if (cin.fail())
{
cout << "bad input";
cin.clear();
cin.ignore();
continue;
}
else
cout << ii << yy << endl;
}
return 0;
}
Streams can be a little confusing if you're unfamiliar with them. It's a large topic that's just going to require more research. Here's an example that should work, to hopefully get you started.
int main(int argc, char* argv[])
{
bool test = true;
while ( test ) {
std::cout << "Enter two integers> ";
int x, y;
// if this fails, stream is bad.
// #note this will fail for any input which cannot be interpreted
// as an integer value.
if (std::cin >> x >> y) {
std::cout << x << " " << y << std::endl;
}
else {
// clear stream error state so we can read from it again.
std::cin.clear();
// check for terminating character; else unknown.
if (std::cin.get() == '|')
std::cout << "Terminator found, exiting." << std::endl;
else
std::cerr << "Error: bad input, exiting." << std::endl;
// in either case the loop terminates.
test = false;
}
}
return 0;
}
Hope this helps. Good luck.
Use the cin.peek() function as follows, before you input the two numbers:
c=(cin >> ws).peek();
if(c=='|')
{
cout<<"exiting";return 1;
}
Note: (cin>>ws) is to get rid of leading whitespaces. Also, c is of type char.
The complete code now looks like this:
int main()
{
int ii = 0;
int yy = 0;
bool test = true;
cout << "Enter two ints" << endl;
while (test)
{
char c;
c=(cin >> ws).peek();
if(c=='|')
{
cout<<"exiting";return 1;
}
cin>>ii, cin>>yy;
if (cin.fail())
{
cout << "bad input";
cin.clear();
cin.ignore();
continue;
}
else
cout << ii << yy << endl;
}
return 0;
}
#include "../../std_lib_facilities.h"
bool CheckForDislike(vector<string> disliked, string slowo) {
int i = 0;
while (i < disliked.size()) {
if (slowo == disliked[i]) {
return true;
}
i++;
}
return false;
}
int main() {
cout << "Enter a word: ";
vector<string> disliked(2);
disliked[0] = "Szpinak";
disliked[1] = "Brokuły";
string slowo = "a";
while (cin >> slowo) {
if (CheckForDislike(disliked, slowo)) {
cout << "Biip\n";
}
else {
cout << slowo << '\n';
}
}
}
Above code should print "Biip" when you enter a word that is in disliked vector.
It doesn't work for words with signs like "ą","ł" basically special signs from my native language. The function returns 1 or true for them, so the problem has to be somewhere in conditional, but i cant see why.
I was able to make a program that has a menu on it. At first, the program is running smoothly. The problem starts to appear when, at a certain point in the program, the user starts inputting something and then navigating the menus again.
Sometimes it will print out integers/characters that were previously entered by the user when pressing the ENTER key in the menu.
I managed to block the inputs with cin.ignore(). But how can I eliminate the display of the (I don't know if its excess or garbage) inside the input buffer whenever the user presses the LEFT and RIGHT arrow keys? Or I think there's even one for UP and DOWN arrow key?
int main()
{
color(FG_WHITE);
bool progFinished = false;
while (!progFinished) {
cout << "[ACTIVITY FOR 26 FEBRUARY 2018]\n";
vector<string> menu = { "Currency Converter","Student Information System" };
int choice = menu_std(menu, FG_YELLOW, false);
bool currencyFinished = false;
bool studentFinished = false;
switch (choice) {
case 0:
while (!currencyFinished) {
cout << "\n\n[CURRENCY CONVERT]\n";
vector<string> curr_menu = { "PHP TO OTHERS","USD TO PHP","YEN TO PHP","EUR TO PHP","BHD TO PHP" };
int currency = menu_std(curr_menu, FG_YELLOW, false);
double value = validation("\nEnter the value", 0, false);
CurrencyConverter convert(currency, value);
cout << "\n\nConvert again? ";
currencyFinished = !menu_yn(FG_YELLOW);
}
system("cls");
break;
case 1:
Studentv2 stud;
stud.LoadFile();
while (!studentFinished) {
cout << "\n\n[STUDENT INFO SYSTEM]\n";
vector<string> stud_menu = { "Add Student","View All Students" };
int stud_choice = menu_std(stud_menu, FG_YELLOW, false);
switch (stud_choice) {
case 0:
stud.AddStudent();
cout << "\n\nDo you want to continue with the Student Info System? ";
stud.SaveFile();
studentFinished = !menu_yn(FG_YELLOW);
break;
case 1:
stud.DisplayStudentInformation();
cout << "\n\nDo you want to continue with the Student Info System? ";
studentFinished = !menu_yn(FG_YELLOW);
break;
}
}
system("cls");
break;
}
cout << "\nContinue using the program? ";
progFinished = !menu_yn(FG_YELLOW);
system("cls");
}
cout << "Press any key to exit.\n";
cin.get();
return 0;
}
Code snippets for some of the functions I used inside my program.
Function menu_std():
int menu_std(std::vector<std::string> &menu, WORD atrribute, bool argument)
{
sleep_for(milliseconds(150));
int elements = menu.size();
int elements_max_size = menu.size() - 1;
int menu_position = 0;
COORD position = getcoordinates();
while (true) {
for (int i = 0; i < elements; i++) {
move(position.X, position.Y + i);
if (i == menu_position) {
color(atrribute);
std::cout << menu[i];
color(FG_WHITE);
}
else {
std::cout << menu[i];
}
}
while (true) {
if (GetAsyncKeyState(VK_UP) < 0 && menu_position != 0) {
menu_position--;
break;
}
if (GetAsyncKeyState(VK_DOWN) < 0 && menu_position != elements_max_size) {
menu_position++;
break;
}
if (GetAsyncKeyState(VK_RETURN) < 0) {
std::cin.ignore(10000, '\n');
if (argument == true) {
sleep_for(milliseconds(100));
COORD previous = getcoordinates();
std::cout << "\n\nAre you sure? ";
bool sure = menu_yn(atrribute);
if (sure) {
clear_output(previous);
return menu_position;
}
else {
clear_output(previous);
break;
}
}
else {
return menu_position;
}
}
sleep_for(milliseconds(50));
}
sleep_for(milliseconds(175));
}
}
Function menu_yn():
bool menu_yn(WORD attribute)
{
sleep_for(milliseconds(150));
COORD currentpos = getcoordinates();
int pos = 0;
while (true) {
move(currentpos);
switch (pos) {
case 0:
color(attribute);
std::cout << "YES";
color(FG_WHITE);
std::cout << " NO";
break;
case 1:
std::cout << "YES";
color(attribute);
std::cout << " NO";
color(FG_WHITE);
break;
}
while (true) {
if (GetAsyncKeyState(VK_RIGHT) < 0 && pos != 1) {
pos++;
break;
}
if (GetAsyncKeyState(VK_LEFT) < 0 && pos != 0) {
pos--;
break;
}
if (GetAsyncKeyState(VK_RETURN) < 0) {
std::cin.ignore(10000, '\n');
if (pos == 0) {
return true;
}
else if (pos == 1) {
return false;
}
}
}
sleep_for(milliseconds(175));
}
}
Function validation()
double validation(std::string question, double limit, bool argument)
{
double userInput;
while (true) {
std::cout << question << " >> ";
while (!(std::cin >> userInput)) {
std::cout << "Error: Non-integer input. " << question << " >> ";;
std::cin.clear();
std::cin.ignore(256, '\n');
}
std::cin.ignore(10000, '\n');
while (userInput > limit && limit != 0) {
std::cout << "Error: Input out-of-bounds. " << question << " >> ";
std::cin >> userInput;
std::cin.ignore(10000, '\n');
}
if (argument) {
return (userInput <= 0) ? 1 : userInput;
}
else {
return userInput;
}
}
}
Screenshot of the problem:
There are numbers appearing whenever I press enter on the menu. I suspect that it comes whenever the user presses the arrow keys before entering the enter.
I'm working through a text book for self study. I can do the while loop no problem, but I have no idea how to do the terminating character.
Here is what I have now:
#include "../../std_lib_facilities.h" // Supplied by book author
int main()
{
int ii = 0;
int yy = 0;
bool test = true;
cout << "Enter two ints" << endl;
while (test)
{
cin>>ii, cin>>yy;
// this if statement doesn't work
if (ii == '|' || yy == '|')
{
test = false;
}
// this if statement catches all bad input, even the terminating '|'
if (cin.fail())
{
cout << "bad input";
cin.clear();
cin.ignore();
continue;
}
else
cout << ii << yy << endl;
}
return 0;
}
Streams can be a little confusing if you're unfamiliar with them. It's a large topic that's just going to require more research. Here's an example that should work, to hopefully get you started.
int main(int argc, char* argv[])
{
bool test = true;
while ( test ) {
std::cout << "Enter two integers> ";
int x, y;
// if this fails, stream is bad.
// #note this will fail for any input which cannot be interpreted
// as an integer value.
if (std::cin >> x >> y) {
std::cout << x << " " << y << std::endl;
}
else {
// clear stream error state so we can read from it again.
std::cin.clear();
// check for terminating character; else unknown.
if (std::cin.get() == '|')
std::cout << "Terminator found, exiting." << std::endl;
else
std::cerr << "Error: bad input, exiting." << std::endl;
// in either case the loop terminates.
test = false;
}
}
return 0;
}
Hope this helps. Good luck.
Use the cin.peek() function as follows, before you input the two numbers:
c=(cin >> ws).peek();
if(c=='|')
{
cout<<"exiting";return 1;
}
Note: (cin>>ws) is to get rid of leading whitespaces. Also, c is of type char.
The complete code now looks like this:
int main()
{
int ii = 0;
int yy = 0;
bool test = true;
cout << "Enter two ints" << endl;
while (test)
{
char c;
c=(cin >> ws).peek();
if(c=='|')
{
cout<<"exiting";return 1;
}
cin>>ii, cin>>yy;
if (cin.fail())
{
cout << "bad input";
cin.clear();
cin.ignore();
continue;
}
else
cout << ii << yy << endl;
}
return 0;
}