Truncated If Statement C++ (Turning letters to numbers) - c++

I am trying to change a series of letters into numbers with C++ and have started by making this code.
However, it appears that the math that calculates the digit1 variable is never getting executed.
Any thoughts?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int qtyofnumbers, num, digit1, counter;
char letters, upperlower;
cout << "Enter a letter: ";
cin >> letters;
for (counter = 0; counter < 8; counter++)
{
if (counter == 3)
cout << "-";
num = static_cast<int>(letters) - static_cast<int>('A');
if (0 <= num && num < 26)
digit1 = (num / 3) + 2;
if (((num / 3 == 6 ) || (num / 3 == 7)) && (num % 3 == 0))
digit1 = digit1-1;
if (digit1 > 9)
digit1 = 9;
cin >> letters;
}
cout << digit1;
return 0;
}

My guess is that the problem is in your input. Are you entering capital letters or lowercase letters? Their ASCII codes are different. So, you probably want to change the code from
num= static_cast<int>(letters)-static_cast<int>('A');
to something like
if (num >= 'a')
num = letters - 'a';
else
num = letters - 'A';
Also, as mentioned by #jtbandes, use the curly braces { and }. Whitespace does not determine scope in C++. Even if it's for only one line of code after your if-statement, it'll save you headaches in the future.

Is the static cast necessary? I recommend using a string stream or just traversing the string character by character using .at() and relying on the ascii values for conversion. http://web.cs.mun.ca/~michael/c/ascii-table.html.

Related

I need help in c++ change cases

#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence ="";
cin >> sentence; //aab
int i;
for (i=0;i=sentence.length();i++){
if (i<=65 && i>=90) {
sentence = sentence[i] + 32;
}
else if (i<=97 && i>=122){ //i=0,
sentence = sentence [i]-32;
}
}
cout << sentence;
return 0;
}
When I enter this code for changing cases of letters it keeps asking me to enter more although I have only one cin in the code why does that happen?
Problem one is inadvertent assignment. Look at your loop condition:
for (i=0;i=sentence.length();i++)
That assigns i rather than comparing it, resulting in an infinite loop. Use < instead of =:
for (i=0; i < sentence.length(); i++)
Problem two is you're comparing the position in the string to the character ranges rather than the character itself, and the comparison is backwards and can never be true:
if (i<=65 && i>=90)
Should be:
if (sentence[i] >= 65 && sentence[i] <= 90)
Same for the lower case range.
Finally, you don't want to change the whole sentence to one character, just that character:
sentence = sentence[i] + 32;
Should be:
sentence[i] = sentence[i] + 32;
Again, same for the lower case range.
With these changes, it seems to work, at least for single words. If you want to do entire sentences, I'd recommend using std::getline(std::cin, sentence); rather than cin >> sentence;.

wraparound c++ for ASCII

I'm Matt, first time posting. I'm in school and learning c++ at the moment and I'm stuck on this problem. I can't seem to find the solution so I'm looking for help.
#include <iostream>
using namespace std;
int main()
{
char ch;
cin >> ch;
if(ch <= 122){
cout << ++ch;
cout << ++ch;
}else if (ch > 122){
cout << static_cast<char>(97)++ch;
cout << static_cast<char>(97)++ch;
}
}
The program is very basic. All it needs to do is be fed a lowercase letter and the program just needs to spit out the next two characters. My problem is that after 'z' I don't know how to wrap back around to 'a'. I've tried to static_cast but it says I can'. I've tried reassigning the variable and it says I can't. I've tried several other basic things but none seem to work.
Thank you in advance for the help!
First, don't use magic numbers like 122 and 97. Use the actual character value.
Second, just declare a string abcdefghijklmnopqrstuvwxyz, and index into that string. This eliminates the need for 122, 97, or any other number. Not only that, you can probably see how to do the problem much easier when dealing with indices such as 0, 1, 25, etc. instead of 122, 97, etc.
Once you do that, a little bit of insight shows that the next two characters will be at position (if positions start at 0), (index + 1) % 26 and (index + 2) % 26. The % is the modulus operator, and it returns the remainder after a division is done.
For example, if the current character is y, the yis located at position 24 of the string. So
(24 + 1) % 26 = 25 % 26 = 25
and
(24 + 2) % 26 = 26 % 26 = 0
So the next two characters are situated at position 25 and position 0, which are z and a.
Take another example: z:
(25 + 1) % 26 = 26 % 26 = 0
and
(25 + 2) % 26 = 27 % 26 = 1
So the next characters after z are a and b.
Basically, when you get an assignment where the data "wraps around" to 0, then the word "remainder" or "modulo arithmetic" should immediately come to mind.
So the final program would look like this:
#include <iostream>
int main()
{
char ch;
const char * alphabet = "abcdefghijklmnopqrstuvwxyz";
std::cin >> ch;
int position1 = ch - 'a'; // get position of input character
int position2 = (position1 + 1) % 26; // get position of next character
int position3 = (position1 + 2) % 26; // get position of next next character
// output results
std::cout << ch << alphabet[position2] << alphabet[position3];
}
Live Example
(assuming that the input is: 'a' - 'z')
Keep It Simple
Solution 1:
#include <iostream>
int main()
{
char ch = 0;
std::cin >> ch; // "fed a lowercase letter"
// "spit out the next two characters"
if (ch < 'y')
std::cout << ++ch << ++ch;
else if (ch == 'y')
std::cout << "za";
else // (ch=='z')
std::cout << "ab";
}
Solution 2:
#include <iostream>
int main()
{
const char * lut = "abcdefghijklmnopqrstuvwxyzab";
char ch = 0;
std::cin >> ch; // "fed a lowercase letter"
ch -= 'a'; // lowercase letter to index
// "spit out the next two characters"
std::cout << lut[++ch] << lut[++ch];
}
Try to use the following code for your problem.
#include <iostream>
using namespace std;
int main()
{
char ch = '\0';
cin >> ch; // "fed a lowercase letter"
char c_next;
c_next = (ch-'a'+1)%26+'a';
cout <<c_next;
c_next = (ch-'a'+2)%26+'a';
cout << c_next;
return 0;
}
Here is one way at going about tackling your problem that is clean and elegant. It is very readable that uses a look up table, converts caps to lowercase using a bit of modulo arithmetic; it also leverages some of the newer features of modern C++ such as range loops.
#include <iostream>
#include <ccytpe> // needed for ::tolower
int main() {
// ascii a-z [97,122]
char alphabet[26] = {}; // 0 initizlize this will be a look up table
int i = 97;
for( auto & c : alphabet ) {
c = static_cast<char>( i );
i++;
}
// check to see if our table is correct
for( auto & c : alphabet ) {
std::cout << c << " ";
std::cout << '\n';
}
std::cout << '\n';
// Alphabet Seems to be fine.
char c = {};
std::cout << "Please enter a lower case character: ";
std::cin >> c;
if( c >= 'A' && c <= 'Z' ) {
::tolower( c ); // make sure that it's not in caps
} else if( c >= 'a' && c <= 'z' ) {
// nothing to do
} else {
std::cout << "Error: input value\n";
return -1;
}
// Now that we have the correct inputs we can show your next two characters.
// Since we know that the ascii table has a range of [97,122] for
// lower case letters and that our array index starts at 0; what we can do
// is a little bit of arithmetic to take the input character and set that
// to the index value of the array above. Then use the array indexing to
// output the next 2 characters. To do this we simply just need to subtract 97 or 'a'
c = c - 'a';
// Now we can print the two lines using the adjusted c value with
// a little bit of modulo arithmetic using the stride, size, or
// length of the alphabet.
int stride = 26;
std::cout << alphabet[++c % stride] << '\n';
std::cout << alphabet[++c % stride] << '\n';
// And we are done!
return 0;
}
This is what the code would look like without the comments and the code to print the whole alphabet:
#include <iostream>
#include <cctype>
int main() {
char alphabet[26] = {};
int i = 97;
for( auto & c : alphabet ) {
c = static_cast<char>( i );
i++;
}
char c = {};
std::cout << "Please enter a lower case character: ";
std::cin >> c;
if( c >= 'A' && c <= 'Z' ) {
::tolower( c );
} else if( c >= 'a' && c <= 'z' ) {
// nothing to do
} else {
std::cout << "Error: input value\n";
return -1;
}
c = c - 'a';
int stride = 26;
std::cout << alphabet[++c % stride] << '\n';
std::cout << alphabet[++c % stride] << '\n';
return 0;
}

Why isn't my palindrome checker working?

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.

Read digits from an int and counting them

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.

C-string assignment using for loop

I think this is a relevant topic, while browsing this forum and tutorial I have tweaked my c-string to the proper format(I think) but there's just one topic missing. How can we take an integer, using a for loop, and assign the c-string values from the integer.
I'm just focusing on the integer to binary part right now and I'm sure my number manipulation is solid. However, my prof said we needed to assign the binary values to a c-string. And I'm trying this, it's telling me I'm using a const char and a char* via the compiler. I'm not sure how this is happening, or how to prevent it.
Here's my source code:
//sample integer to binary
#include <iomanip>
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main()
{
int num; //the number a user enters
int rem; //the remainder, the 1 and 0 of the binary number
int x; //a variable to store the number after division
char binary[10]; //c-string initialized to 10, perhaps that is too many.
cout << "Enter a number: ";
cin >> num;
for (int i = 0; i < 10; i++)
{
x = num / 2;
cout << x << endl; //this shows that the code is working
rem = num % 2;
cout << num << endl; //this also shows the code is working
char r = (char)rem; //These two lines of code are
strcpy(binary[i], r); //preventing compilation
cout << binary[i] << endl; // this is diagnostic
num = x;
}
cout << "The number " << num << " is " << binary[5] << " in binary.\n";
return 0;
}
Thanks you two, I've been able to make this work (almost).
I'm still getting some unexpected behavior, and I'm not sure how big to initialize the array to, I don't think that it would matter too much, but I don't know exactly how big of numbers the graders use to test.
Anyways, here's the new code:
#include <iomanip>
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
int main()
{
int num; //the number a user enters
int rem; //the remainder, the 1 and 0 of the binary number
int x; //a variable to store the number after division
char binary[5] = {'0', '\0'}; //c-string initialized to 10, perhaps that is too many.
cout << "Enter a number: ";
cin >> num;
for (int i = 0; i < 10; i++)
{
x = num / 2;
//cout << x << endl; //this shows that the code is working
rem = num % 2;
//cout << num << endl; //also shows the code is working
binary[i] = '0' + rem; //not sure what this is doing, but it works.
//cout << binary[i] << endl; // this is diagnostic
num = x;
}
cout << "The number " << num << " is " << binary << " in binary.\n";
return 0;
}
And here's the output:
Enter a number: 5
The number 0 is 1010000000# in binary.
It should show the number, the initial number, and say 101, without the 0's and the # sign.
strcpy is for copying entire NUL-terminated string. If you want to set just one character, you can use =.
binary[i] = r;
However, if you want the line cout << binary[i] to work right, or to treat binary as a C string later, you need to store ASCII digits:
binary[i] = '0' + r;
Don't forget to add a terminating NUL to your string, right now it isn't a C-style string at all.
The arguments to strcpy() are char*, not char. The second argument must point to a null-terminated string, but r is just a single character. To assign a character to an element of an array, do:
binary[i] = r;
But you don't want the binary value of rem, you want the character that represents that binary value. It should be:
char r = '0' + rem;
In order to print binary as a string, you need to give it a null terminator. Since you're putting 10 digits into the string, you need to declare an extra character to hold the terminator, and initialize it with zeroes so it will be terminated properly.
char binary[11] = {0};
And if you want to print the whole string, you shouldn't reference binary[5], you should print the whole array:
cout << "The number " << num << " is " << binary << " in binary.\n";
In addition to problems already pointed out, you get binary digits in the reverse order. You have to count significant digits in your binary representation and reverse characters when you're done.
You didn't initialize the character buffer correctly that's why you are getting garbage in the print out.
As for the buffer size, you need as many characters as there are bits in the integer type you are converting plus one more for the terminating '\0', so for a 32-bit number you need 33 character size buffer. And that's important because if you overrun your buffer, quite nasty things will happen.
And one more note: I assume that numbers you are supposed to convert to a string representation are unsigned, so be explicit about it. Below is a quick and dirty implementation with some minimal error checking:
char *unsigned_to_binstr (unsigned n, char *binary, int buf_len)
{
int i, j;
if (buf_len < 2)
return NULL;
i = 0;
do {
binary[i++] = '0' + n % 2;
n /= 2;
} while (n && i < buf_len);
for (j = 0; j < i / 2; ++j) {
char temp = binary[j];
binary[j] = binary[i-j-1];
binary[i-j-1] = temp;
}
binary[i] = '\0';
return binary;
}
After everyone's comments, and my own research via my textbook I was able to formulate a somewhat working function. However, in the process I began to wonder about the garbage problem, so my solution.. Truncate! I added if clauses (tried to think of a loop representation but didn't get any ideas) and at the end I just use the length provided via if clauses and subtract 1, which should give me the appropriate bit size for the number. Using what basic c++ knowledge we've covered in class this is the solution I came up with, however crude and inefficient it might be!
I want to thank all of you, I couldn't have gotten past the point I was stuck at if it weren't for you!
Here's my rough final revision:
//sample integer to binary
#include <iostream>
using namespace std;
int main()
{
int num; //the number a user enters
int rem; //the remainder, the 1 and 0 of the binary number
int x; //a variable to store the number after division
int l; //length of c-string function
cout << "Enter a number: ";
cin >> num; //user input
if ((num == 1) || (num == 0)) // the following 17 lines of code are to truncate the string size.
l = 2;
if ((num > 1) && (num < 4))
l = 3;
if ((num >= 4) && (num <= 7))
l = 4;
if ((num >= 8) && (num <= 15))
l = 5;
if ((num >= 16) && (num <= 31))
l = 6;
if ((num >= 32) && (num <= 63))
l = 7;
if ((num >= 64) && (num <= 127))
l = 8;
if ((num >= 128) && (num <= 255))
l = 9;
if ((num > 255))
cout << "This number is too large for this string\n"; // I don't think the binary sequence should be larger than 16 bits.
char binary[l]; //c-string initialized to size according to the truncation rules above
for (int i = l - 1; i > 0; i--) //goes in reverse order, as binary counts from bottom to top.
{
x = num / 2;
rem = num % 2;
num = x;
binary[i] = '0' + rem; // added an
}
for (int i = 0; i <= l-1; i++)
{
cout << binary[i];
}
cout << " in binary.\n";
return 0;
}