I'm trying to declare this string as Invalid but in an input like this:
59G71341 or 8pjf7h14sx13 or 60s1v344
My output is getting approved through my string if statement and is getting listed as Valid.
Could anyone guide me to why its passing through my if statement and labeling Valid!!
I haven't learned how to use a debugger yet so bare with me.
Task description:
Declare a Boolean variable named goodPasswd. Use goodPasswd to output "Valid" if secretStr contains no more than 5 digits and secretStr's length is greater than or equal to 5, and "Invalid" otherwise.
Ex: If the input is 80796, then the output is:
Valid
Ex: If the input is XBdg, then the output is:
Invalid
#include <iostream>
using namespace std;
int main()
{
string secretStr;
bool goodPasswd = false;
cin >> secretStr;
int counter = 0;
for (int i = 0; i < secretStr.length(); ++i)
{
if ((secretStr[i] >= 0) && (secretStr[i] <= 9))
{
++counter;
}
} //approves string if both true
if ((counter <= 5) && (secretStr.length() >= 5))
{
goodPasswd = true;
}
else
{
goodPasswd = false;
}
if (goodPasswd)
{
cout << "Valid" << endl;
}
else
{
cout << "Invalid" << endl;
}
return 0;
}
if ((secretStr[i] >= 0) && (secretStr[i] <= 9))
should be
if ((secretStr[i] >= '0') && (secretStr[i] <= '9'))
0 and 9 are integers, but you are comparing characters, so you need to use the characters '0' and '9', or you could just use the isdigit function.
if (isdigit(secretStr[i]))
isdigit is declared in #include <cctype>
Not related to your question but you don't need to goodPasswd variable. Simply
if (counter <= 5 && secretStr.length() >= 5)
{
cout << "Valid" << endl;
}
else
{
cout << "Invalid" << endl;
}
seems a bit cleaner to me.
Related
I was solving a problem . Where i was comparing two array ,one is int and other is string .
inside for loop everything was fine until i inserted a else condition.Before else condition for loop was just fine . it was giving equel index for two array . But after else condition it was giving both the condition together.
here are my code-
#include <iostream>
#include <string>
using namespace std;
int main()
{
int last_digit[] = {61, 71, 11, 21, 32, 19, 27, 31};
string places[] = {"Brasilia", "Salvador", "Sao Paulo", "Rio de Janeiro", "Juiz de Fora", "Campinas", "Vitoria", "Balo Horizonte"};
int digit;
cin >> digit;
for (int i = 0; i <= 7; i++)
{
if (digit == last_digit[i])
cout << places[i]<< endl;
else
cout << "Sorry! no number." << endl;
}
Now i want to print the array values as index which is right without the else condition. But i when an input isn't in the array the program should give else condition once. But it is giving both if else condition. Here are my output .
emamulhaqueemon#Emams-MacBook-Air snake % cd "/Users/emamulhaqueemon/main/snake/" && g++ test.cpp -o test && "/Use
rs/emamulhaqueemon/main/snake/"test
11
Sorry! no number.
emamulhaqueemon#Emams-MacBook-Air snake %
now why this is happening and how can i make this right .Please anybody give the answers.
Your loop currently does too much:
find digit in last_digit
print corresponding element according to found digit
print no matching elements (whereas you want to print when find fails).
You might split that in smaller parts.
With functions from std, you might do:
const auto it = std::find(std::begin(last_digit), std::end(last_digit), digit);
if (it == std::end(last_digit)) { // Not found
std::cout << "Sorry! no number." << std::endl;
} else { // Found
const auto index = std::distance(std::begin(last_digit), it);
std::cout << places[index] << std::endl;
}
Demo
Just place the output statement in the else part of the if statement outside the for loop. For example
bool found = false;
for (int i = 0; i <= 7; i++)
{
if ( digit == last_digit[i])
{
found = true;
cout << places[i]<< endl;
}
}
if ( !found )
{
cout << "Sorry! no number." << endl;
}
If the array last_digit does not contain duplicate values and you need to find only the first occurrence of the value digit in the array then the loop can look the following way
for (int i = 0; !found && i <= 7; i++)
{
if ( digit == last_digit[i])
{
found = true;
cout << places[i]<< endl;
}
}
if ( !found )
{
cout << "Sorry! no number." << endl;
}
I am writing filter program grouping kindergarten, preschool and school for ages I wrote if program but it outputs conditions wrong who is willing to take look at my program?
#include<iostream>
using namespace std;
int main() {
int input;// age
int kindergarden , preschool , school;
cin >> input;
if (2 <= 4)
{
cout << "kindergarden" << "\n\n";
if (5 <= 6)
{
cout << "preschool" << "\n\n";
}
else (7 <= 15);
{
cout << "school" << "\n\n";
}
}
}
Your first if statement is if (2 <= 4). This will always be true. 2 is always less than 4. Inside that if statement, is another if statement, asking if 5 <= 6. This will always be true also. Thus, it will output "kindergarten preschool".
I assume you want to check if input is within the two values in your if statements. To do so, you would write
if(2 <= input && input <= 4)
Also, you should bring the second if statement outside of the first. To do that, you should put your } before the second if statement, not after the last one.
Edit: As YSC pointed out, there's another issue: else (7 <= 15);. There are two issues with this:
1) It should be else if(condition), as plain else statements do not expect a condition.
2) It should not end with ;. It should end with { to hold the code that should be executed if the condition is true.
Your first if is wrapped around two others. Because you 're used flat indentation of source code, it's very hard to spot.
if (2 <= input && input <= 4)
{
cout << "kindergarden" << "\n\n";
} // here was your mistake
else if (5 <= input && input <= 6)
{
cout << "preschool" << "\n\n";
}
else if (7 <= input && input <= 15) // ; another mistake
{
cout << "school" << "\n\n";
}
You can make it into one loop actually, in a dozen various ways
#include<iostream>
#include<string>
using namespace std;
int main() {
int input = 0;// age
const struct Cat
{
int age;
string category;
} classes[] = { {2, "kindergarden"}, {5, "preschool"}, {7, "school"}, {16, ""} };
cin >> input;
// without range loop this looks tricky
for(const Cat *c = std::end(classes)-1; c >= std::begin(classes); c-- )
if ( input >= c->age )
{
std::cout << c-> category;
break;
}
}
The only advantage would be aggregation of conditions in one place. Of course, there can be more parameters for condition, e.g. upper and lower bracket instead of lower only.
I can't for the life of me get my code to work. It identifies palindromes correctly, but for some reason, some non-palindromes words get marked as palindromes. Not all, just sum. And biggest headache of all, I can't figure out the correlation between of the non-palindromes that pass.
Any other feedback is appreciated.
#include <iostream>
#include <ctype.h>
#include <string.h>
#include <limits>
using namespace std;
int main() {
const int a(15);
char Line[a + 1];
int i;
do {
cout << "Enter a possible palindrome" << endl;
cin.getline(Line, a + 1);
if (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else;
for (int i = 0; i < strlen(Line); i++) {
Line[i] = (char)tolower(Line[i]);
}
int c = strlen(Line);
for (int i = 0; i < c / 2; i++) {
while (!(((int)Line[c - 1 - i] >= 'a' && (int)Line[c - 1 - i] <= 'z') || ((int)Line[c - 1 - i] >= 'A' && (int)Line[c - 1 - i] <= 'Z'))) {
c--;
}
if ((Line[i] == Line[c - 1 - i]))
{
cout << "is a Palindrome" << endl;
}
else
cout << Line << " is not a palindrome." << endl;
break;
}
} while (strcmp(Line, "END") != 0);
return 0;
The string is a palindrome if the condition Line[i] == Line[c-1-i] holds for all i < c/2. You print out that its a palindrome provided two of the characters match.
Eg: Your program would say:
"abdca" //is a palindrome since the first and last character match.
I think your code is intricacy a bit. Let's assume that the input is always readable, so you just need to cin >> Line;. Let n is length of string. Now we use a loop from 0 to n / 2 to check the symmetry of string. If Line[i] != Line[n - i - 1] that means Line is not symmetry (palindrome) then we just need to print the result and return 0. If the program pass the loop that mean Line is pallindrome. This problem is quite easy. For me, the way you think of it is complex a bit.
I'm writing a program that accepts a card rank as an input, then coverts these ranks into the values they represent. So some examples would include A, 5, 10, K. I've been trying to figure out ways to do this.
I thought about accepting it as a char, then converting it, like so...
char input = 0;
std::cin >> input;
if(input < 58 && input > 49) //accepting 2-9
{
//convert integers
}
else if(input < 123 && input > 64)
{
//convert characters and check if they're valid.
}
And that would work...except for 10 unfortunately. What's an option that works?
Why not use the code you have, and just have a special case, in a third if block, to handle 10?
Since there's no valid input besides 10 that starts with a 1, this should be pretty straightforward:
char input = 0;
std::cin >> input;
if(input < 58 && input > 49) //accepting 2-9
{
//convert integers
}
else if(input < 123 && input > 64)
{
//convert characters and check if they're valid.
}
else if(input == 49){ //accepts 1
std:cin >> input; //takes a second character
if(input == 48){ //this is 10
//do stuff for 10
}
else{
//throw error, 1 followed by anything but 0 is invalid input
}
}
Why not use std::regex when we're in 2016? #Michael Blake, is it a hard requirement to implement the parsing by hand?
I've been able to achieve the desired effect like so:
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::regex regexp("[KQJA2-9]|(10)");
std::string in;
for (;;) {
std::cin >> in;
std::cout << (std::regex_match(in, regexp) ? "yes" : "no") << std::endl;
}
}
We should use char array of size 2 because we can not store 10 in a char. Here is the sample program :
#include <iostream>
#include <string>
#include <stdlib.h>
#include <sstream>
using namespace std;
int main()
{
char s[2];
cin >> s;
if( (s[0] < 58 && s[0] > 48) && ( s[1] == '\0' || s[1] == 48) )
{
int m;
m = atoi(s);
cout << "integer " << m << endl;
}
else if(s[0] < 123 && s[0] > 64)
{
char c;
c = s[0];
cout << "char " << c << endl;
}
else
{
cout << "invalid input" << endl;
}
return 0;
}
Alright so I've been looking though Google and on forums for hours and can't seem to understand how to solve this problem.
I need to write a program that first determines if the number entered by the user is a base 5 number (in other words, a number that only has 0s, 1s, 2s, 3s, and 4s in it). Then, I have to count how many 0s, 1s, 2s, etc are in the number and display it to the user.
I've seen people saying I should convert int to a string and then using cin.get().
I noticed that I can't use cin.get() on a string, it needs to be a char.
I can only use a while loop for this assignment, no while... do loops.
Any help is appreciated!!
Here's what I have so far, obviously with all my mistakes in it:
//----------------------------------------------
// Assignment 3
// Question 1
// File name: q1.cpp
// Written by: Shawn Rousseau (ID: 7518455)
// For COMP 218 Section EC / Winter 2015
// Concordia University, Montreal, QC
//-----------------------------------------------
// The purpose of this program is to check if the
// number entered by the user is a base of 5
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
// Declaring variables
int number;
int zeros;
int ones;
int twos;
int threes;
int fours;
bool base5;
// Get data and calculate
cin >> number;
string numberString = to_string(number);
// Determine if the number is a base 5 number
while (cin.get(numberString) == 0 || cin.get(numberString) == 1 ||
cin.get(numberString) == 2 || cin.get(numberString) == 3 ||
cin.get(numberString) == 4)
base5 = true;
// Determine the number of each digits
zeros = 0;
ones = 0;
twos = 0;
threes = 0;
fours = 0;
return 0;
}
Several things you need to beware of:
One way to get a specific character from a std::string is by []. e.g.
std::string myString{"abcdefg"};
char myChar = myString[4]; // myChar == 'e'
cin.get(aString) is not trying to get data from aString. It continues to get data from stdin and store in aString. Once you have get the data and put into the string, you can simply manipulate the string itself.
a short piece of code that will count number of vowel in a string. If you can understand it, there should be no problem doing your work. (Haven't compiled, probably some typos)
std::string inputString;
std::cin >> inputString;
// you said you need a while loop.
// although it is easier to with for loop and iterator...
int i = 0;
int noOfVowels = 0;
while (i < inputString.length()) {
if (inputString[i] == 'a'
|| inputString[i] == 'e'
|| inputString[i] == 'i'
|| inputString[i] == 'o'
|| inputString[i] == 'u' ) {
++noOfVowels;
}
++i;
}
std::cout << "number of vowels : " << noOfVowels << std::endl;
Well you can try this approach. This will solve your needs I guess.
#include <iostream>
#include <string>
#include <sstream>
#include <conio.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int number=0;
int zeros=0;
int ones=0;
int twos=0;
int threes=0;
int fours=0;
bool valid=true;;
int counter = 0;
cout<<"Enter the number: ";
cin >> number;
stringstream out;
out << number; //int to string
string numberString = out.str();
cout<<"\n\nNumber after string conversion : "<<numberString;
cout<<"\nPrinting this just to show that the conversion was successful\n\n\n";
while (counter < numberString.length())
{
if (numberString[counter] == '0')
zeros++;
else if(numberString[counter] == '1')
ones++;
else if(numberString[counter] == '2')
twos++;
else if(numberString[counter] == '3')
threes++;
else if(numberString[counter] == '4')
fours++;
else
valid=false;
counter++;
}
if(valid==true)
{
cout<<"\nZeros : "<<zeros;
cout<<"\nOnes : "<<ones;
cout<<"\nTwos : "<<twos;
cout<<"\nThrees : "<<threes;
cout<<"\nFours : "<<fours;
}
else
cout<<"\n\nInvalid data...base of 5 rule violated";
_getch();
return 0;
}
If you don't want to use std::string then use characters, first loop over the input from the user until ENTER is pressed.
char ch = 0;
while ((ch = cin.get()) != '\n')
{
...
}
For each character read, check if it is a digit (std::isdigit) and if it is in the range 0..4, if not quit and give some message of not being base 5
have an array of ints to keep track of the frequency of the digits
int freq[5] = {0,0,0,0,0};
after you have checked that the character is valid subtract the ascii value from the digit and use that as index in the array, increment that:
freq[ch - '0']++;
e.g.
char ch;
int freq[5] = {0};
while ((ch = cin.get()) != '\n')
{
cout << ch;
freq[ch-'0']++;
}
for (int i = 0; i < sizeof(freq)/sizeof(freq[0]); ++i)
{
cout << static_cast<char>(48+i) << ":" << freq[i] << endl;
}
Here's a useful function that counts digits:
// D returns the number of times 'd' appears as a digit of n.
// May not work for n = INT_MIN.
int D(int n, int d) {
// Special case if we're counting zeros of 0.
if (n == 0 && d == 0) return 1;
if (n < 0) n = -n;
int r = 0;
while (n) {
if (n % 10 == d) r++;
n /= 10;
}
return r;
}
In your code you can use this naively to solve the problem without any further loops.
if (D(n, 5) + D(n, 6) + D(n, 7) + D(n, 8) + D(n, 9) != 0) {
cout << "the number doesn't consist only of the digits 0..4."
}
cout << "0s: " << D(n, 0) << "\n";
cout << "1s: " << D(n, 1) << "\n";
cout << "2s: " << D(n, 2) << "\n";
cout << "3s: " << D(n, 3) << "\n";
cout << "4s: " << D(n, 4) << "\n";
You could also (or should also) use loops here to reduce the redundancy.