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)];
Related
#include <iostream>
using namespace std;
int main()
{
string sentence;
int countv = 0, countc = 0, countspace = 0, number, s = 1;
cout << "How many sentence would you like to check? - ";
cin >> number;
while(s <= number)
{
cout << "\nSentence " << s << ":";
cin.ignore();
getline(cin, sentence);
for(int i = 0; i < sentence.length(); i++)
{
if(sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u')
countv++;
else if(isspace(sentence[i]))
countspace++;
else
countc++;
}
cout << "\nSentence " << s << " result:";
cout << "\nThere are " << countv << " vowels in the sentence.";
cout << "\nThere are " << countc << " consonants in the sentence.";
cout << "\nThere are " << countspace << " whitespace in the sentence.";
countc = 0, countv = 0, countspace = 0;
s++;
cout << "\n";
}
}
I'm trying to count the number of vowels and consonants in multiple strings but, for some reason, it only gives the correct output for the first string.
I've noticed that, for the next strings (2nd, 3rd and so on), it does not count the first letter of the string. Why is this?
The code is ignoring the first character of each of the strings after the first because you are telling it to ignore those on input … with the call to cin.ignore(). That call should not be inside the loop but immediately before it, so as to ignore the newline that is left in the input stream after the cin >> number extraction.
Note that the call to getline does not leave that newline in the stream's buffer; see this cppreference page:
… the next available input character is delim, as tested by
Traits::eq(c, delim), in which case the delimiter character is
extracted from input, but is not appended to str.
Here's a suitably modified version of your code:
#include <string>
#include <iostream>
using std::cin, std::cout;
int main()
{
std::string sentence;
int countv = 0, countc = 0, countspace = 0, number, s = 1;
cout << "How many sentence would you like to check? - ";
cin >> number;
cin.ignore(); // Call ignore HERE (once) to skip the newline left in the buffer from the above!
while (s <= number)
{
cout << "\nSentence " << s << ":";
// cin.ignore(); WRONG!
std::getline(cin, sentence);
for (size_t i = 0; i < sentence.length(); i++)
{
if (sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u')
countv++;
else if (isspace(sentence[i]))
countspace++;
else
countc++;
}
cout << "\nSentence " << s << " result:";
cout << "\nThere are " << countv << " vowels in the sentence.";
cout << "\nThere are " << countc << " consonants in the sentence.";
cout << "\nThere are " << countspace << " whitespace in the sentence.";
countc = countv = countspace = 0; // Nicer than the dodgy use of the comma!
s++;
cout << "\n";
}
}
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
This question already has answers here:
Why is this only returning "yes"
(2 answers)
Closed 6 years ago.
I'm making my first project c++. It's a simple temperature converter.
I made a test section [code 1] with if statements. the if statement would compare the user input. for example if you user typed c and then k(Celsius-Kelvin). it should run the function[code 2] CtoK(); but i doesn't it runs all function why does it do this?
It try to use return but i didn't(it also didn't gave a error so i kept it)
If you guys see something else pls say it Code on pastebin
Also thinks to keep it mind:
Just stated to learn C++
Not native English so if there are spelling and grammar mistakes please say it so i can learn form it
[code 1]
void whatToWhat(char firstDegrees, char secondDegrees) {
if (firstDegrees == 'C' || 'c') {// tests if the user want form c to f
if (secondDegrees == 'F' || 'f') {
CtoF();
}
}if (firstDegrees == 'C' || 'c') {// tests if the user want form c to k
if (secondDegrees == 'K' || 'k') {
CtoK();
}
}if (firstDegrees == 'F' || 'f') {// tests if the user want form f to c
if (secondDegrees == 'C' || 'c') {
FtoC();
}
}if (firstDegrees == 'F' || 'f') {// tests if the user want form f to k
if (secondDegrees == 'K' || 'k') {
FtoK();
}
}if (firstDegrees == 'K' || 'k') {// tests if the user want form k to f
if (secondDegrees == 'F' || 'f') {
KtoF();
}
}if (firstDegrees == 'K' || 'k') {// tests if the user want form k to c
if (secondDegrees == 'C' || 'c') {
KtoC();
}
}
}
[code 2]
void CtoF() {// c to f furmula
double input;
cout << "Enter a number[Celsius-Fahrenheit]" << endl;
cin >> input;
cout << "it's " << input * 1.8 + 32 << " Fahrenheit " << endl;
return;
}
void CtoK() {// c to k furmula
double input;
cout << "Enter a number[Celsius-Kelvin]" << endl;
cin >> input;
cout << "it's " << input + 273.15 << " Kelvin " << endl;
return;
}
void FtoC() {//f to c furmula
double input;
cout << "Enter a number[Fahrenheit-Celsius]" << endl;
cin >> input;
cout << "it's " << input / 1.8 - 32 << " Celsius " << endl;
}
void FtoK() {//f to k furmula
double input;
cout << "Enter a number[Fahrenheit-Kelvin]" << endl;
cin >> input;
cout << "it's " << input / 1.8 - 32 + 273.15 << " Kelvin " << endl;
return;
}
void KtoF() {// k to f furmula
double input;
cout << "Enter a number[Kelvin-Fahrenheit]" << endl;
cin >> input;
cout << "it's " << (input - 273.15) * 1.8 + 32 << " Fahrenheit " << endl;
}
void KtoC() {// k to c furmula
double input;
cout << "Enter a number[Kelvin-Celsius]" << endl;
cin >> input;
cout << "it's " <<273.15 - input << " Celsius " << endl;
return;
}
if(firstDegrees == 'K' || 'k') will always evaluate to true since k as it is is Not Null, means Valid, means True.
You need to write all your expressions in a similar way to this: (firstDegrees == 'K' || firstDegrees == 'k')
Also, you would want to add elses after each if, for better and clearer logic control.
I am having a bit of trouble with if statements and strings/characters in c++. Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "-----------------------------" << endl;
cout << "|Welcome to Castle Clashers!|" << endl;
cout << "-----------------------------" << endl;
cout << "Would you like to start?" << endl;
string input;
cout << "A. Yes ";
cout << "B. No " << endl;
cin >> input;
if(input == "a" || "A"){
cout << "Yes" << endl;
}else{
if(input == 'b' || 'B'){
return 0;
}
}
return 0;
}
At my if statement it checks if the string input is equal to yes, and if it is not it should go to the else statement. This is where the trouble began, once I ran my program in the console when I type anything besides "a" or "A" it still says yes. I've tried doing it with chars/characters but I get the same output. Could anyone assist me?
It should be input == "a" || input == "A". You have to test each case individually. Right now your code is equivalent to (input == "a") || "A", which evaluates to true because "A" decays to a non-zero pointer.
"A" and 'B' will always be true in typical implementation.
You should also compare input against them.
Also compareing std::string with char doesn't seem supported, so you should also use string literals for b and B.
Try this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "-----------------------------" << endl;
cout << "|Welcome to Castle Clashers!|" << endl;
cout << "-----------------------------" << endl;
cout << "Would you like to start?" << endl;
string input;
cout << "A. Yes ";
cout << "B. No " << endl;
cin >> input;
if(input == "a" || input == "A"){
cout << "Yes" << endl;
}else{
if(input == "b" || input == "B"){
return 0;
}
}
return 0;
}
C didn't have "real" boolean values - instead, anything that equals 0 is considered false, and anything different from that is considered true. While C++ introduced a bool type, it still maintains the old C behavior for compatibility reasons.
As Cornstalk said, your (input == "a" || "A") is the same as ((input == "a") || ("A")), and "A" != 0, so it always evaluates to true - that's why it'll always enter into that if block. What you want is:
if (input == "a" || input == "A")
The same holds true to the next statement (comparing it to 'B'), but there's one extra problem in there: You're using single quotes ( ' ) instead of double quotes ( " ), which makes it a char instead of a string. To make both variables the same type, just use double quotes, and it'll end up like this:
if(input == "b" || input == "B")
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.