Switch statement to evaluate string input C++ - c++

I am working with a user entered string input and I need to use switch-statements to evaluate each of the entered input. My code below currently evaluates a users string input and looks to see if it is a upper case, number, or special character using ASCII codes. I am now sure how switch-statements work and how I could change an If statement to a switch-statement.
for (int i = 0; i < strlength; i++) //for loop used to check the rules of the password inputted by the user
{
cout << "Testing for upper case characters..." << endl; //displays the cout
tmpi=(int) str1[i]; //stoi function making the string input an integer
if ((tmpi >= 65) && (tmpi <= 90)) //checks if there are two upper case characters in the string
{
cout << "Found an uppercase" << endl;
uppercnt++; //adds to the counter of upper case
state++;
cout << "Now in state q" << state << "..." << endl;
continue;
}
cout << "Testing for digits..." << endl;
if(tmpi >= 48 && tmpi <= 57) //checks if there are two digits in the string
{
cout << "Found a digit" << endl;
digitcnt++; //adds to the counter of digit
state++;
cout << "Now in state q" << state << "..." << endl;
continue;
}
cout << "Testing for special characters..." << endl;
if(tmpi >= 33 && tmpi <= 47 || tmpi >= 58 && tmpi <= 64 || tmpi >= 91 && tmpi <= 96 || tmpi >= 123 && tmpi <= 126) //checks if there are special characters
{
cout << "Found a special char" << endl;
speccnt++; //adds to the counter of special character
state++;
cout << "Now in state q" << state << "..." << endl;
continue;
}
cout << "Character entered was a lower case" << endl;
state++;
cout << "Now in state q" << state << "..." << endl;
} //end for loop
Any advice or examples would help out, thanks.

if perfomance not an issue, I just would use std::count_if:
int upps = std::count_if( pass.begin(), pass.end(), isupper );
int digs = std::count_if( pass.begin(), pass.end(), isdigit );
working example on ideone

Related

How do I set the line marker where my string will start? setw() does not achieve what I need it to

C++ How do I set the line marker where my string will start? setw() does not achieve what I need it to. I need the string to begin at a certain point and end whenever, seems like setw() does the exact opposite. I'll send what the final result needs to look like. Ignore the specifics on obtaining the desired numbers from the input file as I already have everything. I just can't seem to format it correctly on the print screen or in the output file.
I have the headers and the actual content already worked out to provide the correct results. Again, I just can't get the layout to be what I need it to be. (P.S. I'm using a while loop to retrieve the information from a file. and the BP has been converted to int from string)
Here is my code so far. I'm not sure what is happening that is not allowing me to make it match the example above. I've tried every combination of setw(), left, right, internal, etc.
It may not be in order yet, but I was more worried about ensuring I had everything first, and then worrying about format and order. (My ofstream is in comment format while I print screen to check my progress. It will eventually be used. I also already know my file isnt being closed at the end.)
ifstream inputfile;
//ofstream outputfile;
string Patient1;
string Patient2;
string Patient3;
string fname;
string lname;
string bp;
int pos;
int systolic;
int diastolic;
string room;
string stage;
string risk;
inputfile.open("E:\\Patient3E.dat");
//Headers for output
cout << "Note" << setw(5) << "Room" << setw(6) << "Name" << setw(23) << "BP" << setw(18) << "Diagnosis" << endl;
cout << "----" << setw(5) << "----" << setw(26) << "------------------------" << setw(10) << "---------" << setw(17) << "---------------" << endl;
while (inputfile >> fname >> lname >> bp >> room)
// Convert string to int for comparison with numbers
{bp.find("/");
pos = bp.find("/");
bp.substr(0, pos);
systolic = stoi(bp.substr(0, pos));
diastolic = stoi(bp.substr(pos+1));
//else if for determining risk asterisks count
if (((systolic >= 120) && (systolic < 140)) || ((diastolic >= 80) && (diastolic < 90)))
{risk = " *";
}
else if (((systolic >= 140) && (systolic < 160)) || ((diastolic >= 90) && (diastolic < 99)))
{risk = " **";
}
else if ((systolic >= 160) || (diastolic >= 100))
{risk = " ***";
}
else if ((systolic < 120) || (diastolic < 80))
{risk = " ";
}
cout << left << setw(4) << risk << right << setw(5) << room << lname << ", " << fname;
//else if statements for adding + to systolic values equal to or greater than 120
if (systolic < 120)
{cout << setw(11) << systolic << "/";
}
else if (systolic >= 120)
{cout << setw(10) << "+" << systolic << "/";
}
//else if statements for adding + after diastolic for values equal to or greater than 80
if (diastolic < 80)
{cout << setw (0) << diastolic;
}
else if (diastolic >= 80)
{cout << setw(0) << diastolic << "+";
}
//else if statements for determining stage
if (((systolic >= 120) && (systolic < 140)) || ((diastolic >= 80) && (diastolic < 90)))
{stage = "prehypertension";
}
else if (((systolic >= 140) && (systolic < 160)) || ((diastolic >= 90) && (diastolic < 99)))
{stage = "stage 1";
}
else if ((systolic >= 160) || (diastolic >= 100))
{stage = "stage 2";
}
else if ((systolic < 120) || (diastolic < 80))
{stage = "Normal";
}
cout << stage << endl;
}
cout << "Summary" << endl;
cout << "Count" << setw(13) << "Diagnosis" << endl;
cout << "-----" << setw(23) << "-------------------" << endl;
//pause funciton
Pause();
return(0);
}

Infinite loop on checking character in a do while

The goal is to calculate the percentage of marks over 10. Marks are between 0 and 20. I have an issue with the while loop when I click on 'N'. I get an infinite loop.
#include <iostream>
int main() {
float MARK, PERCENTAGE;
int NBR_MARK, NBR_MARK_10;
MARK = 0;
NBR_MARK = 0;
NBR_MARK_10 = 0;
PERCENTAGE = 0;
char R = 'N';
std::cout << "Enter a mark ?" << std::endl;
std::cin >> MARK;
while (MARK < 0 || MARK > 20) {
std::cout << " Please, enter a mark between 0 and 20" << std::endl;
std::cin >> MARK;
}
std::cout << "Do you want to enter a new mark ?" << std::endl;
std::cout << "Click on 'O' to continue and on 'N' to stop" << std::endl;
std::cin >> R;
if ((R != 'N') || (R != 'n'))
std::cout << "You will continue" << std::endl;
do {
std::cout << "Enter a new mark" << std::endl;
std::cin >> MARK;
std::cout << std::endl;
while ((MARK < 0) || (MARK > 20)) {
std::cout << "Please, enter a mark between 0 and 20" << std::endl;
std::cin >> MARK;
std::cout << std::endl;
}
NBR_MARK++;
if (MARK > 10) NBR_MARK_10++;
std::cout << "To stop press 'N'" << std::endl;
std::cin >> R;
}
while ((R != 'N') || (R <= 'n'));
PERCENTAGE = NBR_MARK_10 / NBR_MARK * 100;
std::cout << "Le % de notes > 10 est de: " << PERCENTAGE << " %" << std::endl;
return 0;
}
#include<iostream>
using namespace std;
int main() {
float MARK=0.0, PERCENTAGE=0.0;
int NBR_MARK_10;
float NBR_MARK = 0.0;
NBR_MARK_10 = 0;
char R = 'a';
while(R!='N')
{
std::cout << "Enter a mark ?" << std::endl;
std::cin >> MARK;
while (MARK < 0 || MARK > 20) {
std::cout << " Please, enter a mark between 0 and 20" << std::endl;
std::cin >> MARK;
}
NBR_MARK+=1.0;
if (MARK > 10) NBR_MARK_10++;
std::cout << "Do you want to enter a new mark ?" << std::endl;
std::cout << "Click on 'O' to continue and on 'N' to stop" << std::endl;
cin >> R;
}
PERCENTAGE = (NBR_MARK_10 / NBR_MARK) * 100;
std::cout << "Le % de notes > 10 est de: " << PERCENTAGE << " %" << std::endl;
return 0;
}
use a while loop when your checking the next input of R and make sure you make one of the counter variables to float else youll end up getting percentage as zero for few testcases.
You have two problems with the code. As Sharath Chander P pointed out, there is clearly a logical issue in the code flow. Even if you press 'N' (for the first time) the code block inside do..while will execute since the condition is checked only after executing all the statements inside the do..while loop.
Now to your question on the infinite loop. It is because the expression while ((R != 'N') || (R <= 'n')); will be 'true' when you press the key 'N'. When you press 'N', the value of R will be 78 (ASCII value of 'N'). Since the ASCII value of 'n' is 110, the checking R<='n' will return true. (Clearly 78 is less than 110.)
Since (R!='N') is false and R<='n' is true, the expression while ((R != 'N') || (R <= 'n')); will be evaluated as while(false || true).
Since the result will be "true", the loop will continue.
Now if you press 'n' then the expression will be evaluated as while(true || true) that too will result in "true" and the loop will continue;

If and else Statements in While loop" for C++

I have a question regarding if & else statements in a while loop.
I wanted to establish a few things in my program:
wanted user to only input 4 letter characters without the use of numbers and symbols.
converting each those letters into ints(Ascii val.)
To make it easier to understand if confused,
Program 1st asks for 4 letter word.
User places input. If input contains at least:
a non-letter character, then Program asks User for new Input.
If input only contain letters Program checks input for # of letters.
If input doesn't have ___ :
4 letters, Program asks User for new Input.
Otherwise Program proceeds with determining Int value of each letter
Okay so heres my Program so far: ** not sure if this correct for
#include <iostream>
using namespace std;
int main() {
string input;
int input0 = input[0];
int input1 = input[1];
int input2 = input[2];
int input3 = input[3];
cout << "\nEnter a 4-letter word (Keep it clean!).\n";
while(cin>>input){
cout << endl << input << " has " << input.length() << " letters." << endl;
if (int(input[0]) > 64 || int(input[0]) < 91 || int(input[0]) > 96 || int(input[0]) < 123 ||
int(input[1]) > 64 || int(input[1]) < 91 || int(input[1]) > 96 || int(input[1]) < 123 ||
int(input[2]) > 64 || int(input[2]) < 91 || int(input[2]) > 96 || int(input[2]) < 123 ||
int(input[3]) > 64 || int(input[3]) < 91 || int(input[3]) > 96 || int(input[3]) < 123) {
if (input.length()!=5 && input.length()>3)
cout << "\n the int value of the " << input[0] << " is " << int(input[0]) << endl;
cout << "\n the int value of the " << input[1] << " is " << int(input[1]) << endl;
cout << "\n the int value of the " << input[2] << " is " << int(input[2]) << endl;
cout << "\n the int value of the " << input[3] << " is " << int(input[3]) << endl;
else cout << input << "is not a 4-letter word.\nPlease try again." << endl;
}
else cout << input << " contains number(s) and or symbol(s).\nPlease try again." << endl;
}
}
I got 2 errors:
error: expected '}' before 'else'
error: 'else' without a previous 'if'
This fairly gnarly bunch of statements is to blame:
if (input.length()!=5 && input.length()>3)
cout << "\n the int value of the " << input[0] << " is " << int(input[0]) << endl;
// Not part of if-statement:
cout << "\n the int value of the " << input[1] << " is " << int(input[1]) << endl;
cout << "\n the int value of the " << input[2] << " is " << int(input[2]) << endl;
cout << "\n the int value of the " << input[3] << " is " << int(input[3]) << endl;
else cout << input << "is not a 4-letter word.\nPlease try again." << endl;
You need to enclose all those cout statements (up until the else) in braces {, }.
I'd just like to make a point about the character tests you're doing. It looks like you're checking whether the characters are letters, but are using the least-readable, least-portable approach. Use std::isalpha instead. In fact, you can accomplish the whole thing with this:
if( std::all_of( input.begin(), input.begin() + 4, [](char c){ return (bool)isalpha(c); } ) )
{
//...
}
You should do the tests after ensuring the input is the correct length, or you will have undefined behaviour. So let's do that:
while( cin>>input )
{
cout << endl << input << " has " << input.length() << " letters." << endl;
if( input.length() != 4 )
{
cout << input << "is not a 4-letter word.\nPlease try again." << endl;
}
else if( any_of( input.begin(), input.end(), [](char c){ return !isalpha(c); } ) )
{
cout << input << " contains number(s) and or symbol(s).\nPlease try again." << endl;
}
else
{
// I assume you want to exit the loop here.
break;
}
}
Notice I flipped the all_of statement around to the inverse ("any character is not a letter"), for better readability because the lambda no longer needs a cast for automatic type-deduction:
if( any_of( input.begin(), input.end(), [](char c){ return !isalpha(c); } ) ) ...

"Truncation from int to char" not producing any result

My code can compile but it doesn't return the character asked and it also does not follow the else statement since it will cout the error message after any input from the true if statement. Beginner in C++ so any help is appreciated.
// Python Challenge 2.cpp : This program will take a line of text from the user and then translate each letter 2 over in the alphabet.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
char chChar;
char chChar2;
char chChar_a;
char chChar_b;
int main()
{
//This takes the one letter input from the user:
cout << "Type in a lowercase letter: ";
cin >> chChar;
//for letters a-x
if ((int)chChar >= 97 && (int)chChar <= 120)
char chChar2 = (int)chChar + 2;
cout << "is now: " << chChar2 << endl;
//for the letter y
if ((int)chChar == 121)
{
char chChar_a = '97';
cout << "is now: " << chChar_a << endl;
}
//for the letter z
if ((int)chChar == 122)
{
char chChar_b = '98';
cout << "is now: " << chChar_b << endl;
}
//for everything else
else
cout << "Error: type in a lowercase letter." << endl;
return 0;
}
Your if statement is not correct: you forgot to create a block using { } after it.
As it stands, the code does:
//for letters a-x
if ((int)chChar >= 97 && (int)chChar <= 120)
{
char chChar2 = (int)chChar + 2;
}
// Always runs the next part
cout << "is now: " << chChar2 << endl;
...
And the final else is attached to the if before it:
//for the letter z
if ((int)chChar == 122)
{
char chChar_b = '98';
cout << "is now: " << chChar_b << endl;
}
else
{
cout << "Error: type in a lowercase letter." << endl;
}
To fix this, add the proper brackets { }. An if without the brackets only conditionally executes the next statement, and not the block -- don't let indentations fool you: they have no meaning in C.
So, with this, your fixed code should look like:
//This takes the one letter input from the user:
cout << "Type in a lowercase letter: ";
cin >> chChar;
//for letters a-x
if ((int)chChar >= 97 && (int)chChar <= 120)
{
char chChar2 = (int)chChar + 2;
cout << "is now: " << chChar2 << endl;
//for the letter y
if ((int)chChar == 121)
{
char chChar_a = '97';
cout << "is now: " << chChar_a << endl;
}
//for the letter z
if ((int)chChar == 122)
{
char chChar_b = '98';
cout << "is now: " << chChar_b << endl;
}
}
//for everything else
else
{
cout << "Error: type in a lowercase letter." << endl;
}
return 0;
Starting from this, you can debug your code for further issues.

Stroustrup chapter 4 exercise 6: Improve efficiency

The exercise asks for a code which can convert the user input of the numbers 0-9 either as an integer or string to a string or integer respectively i.e. if0 is entered "zero" will be outputted and vice versa.
string number;
cout << "Let's convert strings to numbers."
<< "Enter value/string of 0-9";
while (number!= "exit")
{
cin >> number;
for (int i=0; i < digits.size(); i++)
{
if (number == digits[i]) cout << i << endl;
}
if (number == "0") cout << digits[0] << endl;
else if (number == "1") cout << digits[1] << endl;
else if (number == "2") cout << digits[2] << endl;
else if (number == "3") cout << digits[3] << endl;
else if (number == "4") cout << digits[4] << endl;
else if (number == "5") cout << digits[5] << endl;
else if (number == "6") cout << digits[6] << endl;
else if (number == "7") cout << digits[7] << endl;
else if (number == "8") cout << digits[8] << endl;
else if (number == "9") cout << digits[9] << endl;
}
digits is a vector class which stores the strings "zero", "one" etc.
This code works fine but I don't like the long chain of if/else if statements but I can't figure out a way to convert the integers to strings. Can someone help me make this more efficient? Thanks!
you can use that if number == "0" then number[0] == '0' which is char.
e.i instead if/else statements:
if (number[0] >= '0' && number[0] <= '9' )
std::cout << digits[number[0] - '0'] << std::endl;
else
std::cout << "wrong input - needs to be digit" << std::endl;
string is basically an array of characters, std::string is an array of characters of type char.
For instance these are two legimate ways to declare and initialize strings in c or c++
char s[3] = { '0', '1', '\0' };
char s[3] = "01";
Char value is technically integer (or rather byte) that stores the character code in some encoding (usually ASCII).
For instance the character code of '0' is 48, that of '1' is 49, '2' is 50. And we use this, because we know that
'3' - '0' = 51 - 48 = 3
You could do digits[number[0] - 48] to get rid of the if/else if.
Just use isdigit to check if it's 0-9 http://www.cplusplus.com/reference/clibrary/cctype/isdigit/
And if it is a digit you could convert it to an int using aoti http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
and finally just say
cout << digits[aoti(number)];