I am new to C++, learned it for more than a month. I have a beginner-level knowledge of Python, like creating a list, modifying it, loops, etc. I don't know some codes for C++ that I know in python.
I am making a program for a school class (creative program). This is a part of my code (description at the bottom):
int number, new_one, num_letter;
char one;
cout << "You chose to encypher a message\nPlease choose an integer between 1-25:";
cin >> number;
cout << "How many letters are in your word?";
cin >> num_letter;
if (num_letter == 1)
{
cout << "Enter the first letter";
cin >> one;
new_one = one + number;
cout << "Your encrypted message is '"
<< static_cast<char>(new_one)
<< "' with the code number of "
<< number;
I am making a program where it enciphers and deciphers a message. The user chooses the number of letters of their message (maximum of 10 because I don't know how to use a for-loop in C++ yet). Then, they choose an integer. Then, they enter the letter, hit Enter, enter the letter, and hit Enter for the number of letters in their message (I don't know how to separate strings to chars in C++ yet).
When the user enters their letter and hits Enter, I cin >> that letter into the variable one, which is a char. Then, I add that one to the number the user chose, so the ASCII code of the one increases by the value of the number.
For example, when I enter 3 for number and h for the value of one, 104 (the ASCII code of h) should add up with 3, resulting in 107, which I then would static_cast to a char value.
But, when I add h and 3, instead of creating 107, it creates 155. Same for other variables. I tried cout'ing static_cast<int>(one) (in this case, the letter h) and number (which is 3). They printed 104 and 3.
But, when I add those two values, it prints 155. Why is this happening?
This is my solution. Hope it helps!
#include <iostream>
using namespace std;
int main()
{
int offset = 0;
int num_with_offset;
int size;
// Gets offset from user
do{
cout << "You chose to encypher a message\nPlease choose an integer between 1-25: ";
cin >> offset;
} while (offset < 1 || offset > 25);
// Gets letters in word
do{
cout << "Letters in word: ";
cin >> size;
} while(size < 0);
// Given size, init arrays
int number[size];
char one[size];
// Conversion from char to int
for(int i = 0; i < (sizeof(one)/sizeof(one[0])); i++)
{
cout << "Enter character " << (i + 1) << ": ";
cin >> one[i];
num_with_offset = one[i] + offset;
// Converts ASCII to integer and stores it into array
number[i] = static_cast<int>(num_with_offset);
}
// Prints out the new encrypted message
for(int j = 0; j < (sizeof(number)/sizeof(number[0])); j++)
{
cout << "Your encrypted message is: "
<< number[j] << " , with the code number: "
<< offset << "." << endl;
}
cout << endl << endl;
return 0;
}
Related
I am wondering how to only allow inputs for a cin which are within the int data range.
// This program counts the number of digits in an integer
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i, k;
cout << setw(20) << "Value Entered" << setw(20) << "Number of Digits" << endl;
while(1==1)
{
k = 1;
cout << setw(10) << "";
cin >> i;
while(i > 2147483647 || i < -2147483648)
{
cout << setw(10) << "";
cin >> i;
}
while( i / 10 > 0)
{
i = i / 10;
k++;
}
cout << setw(30) << k << endl;
}
return 0;
}
With the method I have it just gets stuck in the loop repeating 1.
EDIT:
Sample Output Format (Required)
"Value Entered" "Number of Digits"
14 2
225 3
-1000 4
Sample Output (What I have)
Value Entered Number of Digits
45
2
456
3
258
3
-2546
4
The extraction will fail if the number falls outside of the range for the type that it's being read into. When this happens the state of the stream will be set to failure, so you simply need to check for this state, and then reset the stream to a valid state:
while (!(cin >> i)) {
cin.clear();
cin.ignore(numeric_limit<streamsize>::max(), '\n');
}
clear() clears the error flags and ignore() puts the stream on a new line so that new data can be read. You may need to include <limits> for the code to work.
The condition for your second loop should be while (i > 0). As you had it you were off by one digit.
Giving 5 inputs, program will check which entered character is the greater (assume characters are alphabets here only).
This is the code I've written (All variables are of char data type).
Problem is, it's printing the last entered character every time which makes it obvious the logic is faulty..
Here's the code I've written:
cout << "Enter a character ";
cin >> chr;
for (int i = 0; i < 4; i++)
{
cout << "Enter a character ";
cin >> chr2;
if (chr > chr2)
{
store = chr;
}
else
{
store = chr2;
}
chr = chr2;
}
cout << "Greater character is "<< store << endl;
You are making your code far too complex! What you need to do is first set your 'rolling' maximum (the store variable) to a value lower than any possible input (let's say 0) then run a single loop to read in each of the test characters. On each input, compare the given character to your 'rolling' max and, if it's greater, set that rolling max to the given input.
Something like this:
char store = 0, chr;
for (int i = 0; i < 5; ++i) {
cout << "Enter a character ";
cin >> chr;
if (chr > store) store = chr;
}
cout << "Greatest character is "<< store << endl;
Feel free to ask for further clarification and/or explanation.
The problem here is that you are always comparing with the previous character, not the biggest-seen character.
In my opinion, the control flow can be simplified. Try something like this:
/* Rather than pull the first iteration out of the loop, begin with the minimum value */
char greatest = std::numeric_limits<char>::min();
for(int i = 0; i < 5; i++)
{
std::cout << "Enter a character: " << std::endl;
char input;
std::cin >> input;
/* We only need to replace `greatest` with `input` if `input` is greater */
if(input > greatest)
{
greatest = input;
}
}
std::cout << "Greatest character is: " << greatest << std::endl;
Your code chr = chr2; in the last before line tells the code to store the last entered value in the chr and this means you are comparing only the last and last before entered value in the program,
To change the program to suit your need , Change chr = store; which tells the program to store the greatest char entered to be stored inside char variable .
cin >> chr;
for (int i = 0; i < 4; i++)
{
cout << "Enter a character ";
cin >> chr2;
if (chr > chr2)
{
store = chr;
}
else
{
store = chr2;
}
chr = store;
}
cout << "Greater character is "<< store << endl; ````
Hope this helps!!
I am working on a program that has the user input a letter then a string. Once the string is inputted the program should traverse the string and return the amount of the specific letter within the string. Here is the code I have so far:
#include <iostream>
using namespace std;
void countLetters(char letter[]);
/**********************************************************************
* Prompts the user for a line of input (using getline),
* calls countLetters(), and displays the number of letters.
***********************************************************************/
int main()
{
char letter[256];
countLetters(letter);
return 0;
}
/**********************************************************************
* Function to return the number of letters in a string.
***********************************************************************/
void countLetters(char Letter[])
{
char text[] = " ";
int count = 0;
cout << "Enter a letter: ";
cin >> letter;
cout << "Enter text: ";
cin >> text;
cin.getline(text, 256);
for (int i = (sizeof(text) / sizeof(text[0]) - 2); i >=0; i--)
{
if(text[i])
{
count++;
}
cout << "Number of '" << letter << "'s: " << count << endl;
}
}
/*
The output should be:
Enter a number: e
Enter a string: Hello, programming is fun
Number of 'e's: 1
*/
I have tried researching this and have found no help through this method of counting the amount of letters within the string the user inputs. Any help is appreciated, thank you.
Most issues have been pointed out in the comments. Here's a fixed version:
#include <iostream>
using namespace std;
void countLetters();
/**********************************************************************
* Prompts the user for a line of input (using getline),
* calls countLetters(), and displays the number of letters.
***********************************************************************/
int main()
{
// You create an array in the function, don't need one here, too
// char letter[256];
countLetters();
return 0;
}
/**********************************************************************
* Function to return the number of letters in a string.
***********************************************************************/
void countLetters()
{
// Your method creates an array of only 2 bytes
//char text[] = " ";
char text[256];
int count = 0;
// You forgot to declare letter
char letter;
cout << "Enter a letter: ";
cin >> letter;
// Reading the char leaves a new line. Consume. cin.ignore is another way
cin.getline(text, 256);
cout << "Enter text: ";
cin.getline(text, 256);
// Overly complicated
//for (int i = (sizeof(text) / sizeof(text[0]) - 2); i >=0; i--)
for (int i = 0; text[i]; i++)
{
// Compare to letter
if (text[i] == letter)
{
count++;
}
// This needs to be outside the loop
//cout << "Number of '" << letter << "'s: " << count << endl;
}
cout << "Number of '" << letter << "'s: " << count << endl;
}
In C++, it's almost always better to use std::string instead of raw char arrays, but I'll assume this is an assignment and arrays are required.
forum!
I have a project where we are supposed to add numbers that are length 14 or greater. I did some digging and realized that there is no current type that takes numbers this big. So, I have the user enter the numbers as a string and the numbers they would like to add are stored in a static string array.
I would like to add the numbers from the static array together. The issue is I have no idea how to deal with numbers this large. I am assuming you would have to convert the string values into int's and add them up one by one? I am having a big issue coming up with the logic for this. Any help would be appreciated.
If not, if you can provide some context which could help me come up with some logic.
The only library functions I can use is iostream and string.
Here is my code if you'll like to see my logic! I have some test cases I am trying to figure out so please ignore the comment outs. But, if you run the code you should get a better sense of what I am trying to get out. I am trying to sum up the numbers the user enters.
#include <iostream>
#include <string>
using namespace std;
void amountOfNumbers(string &userAmount, int MIN_AMOUNT, int MAX_AMOUNT){
//string alpha = "abcdefghijklmnopqrstuvwxyz";
cout << "How many numbers? -> ";
cin >> userAmount;
cout << endl;
while(!userAmount.find("abcdefghijklmnopqrstuvwxyz")){
cout << "ERROR: must be a number, try again ->";
cout << userAmount;
//cin.clear();
//cin.ignore(1000, '\n');
cin >> userAmount;
cout << endl;
}
int temp = stoi(userAmount);
while((temp < MIN_AMOUNT) or (temp > MAX_AMOUNT)){
cout << "ERROR: Program can only take in " << MIN_AMOUNT << " - "<< MAX_AMOUNT << " numbers. Try again ->";
cin >> userAmount;
cout << endl;
temp = stoi(userAmount);
}
}
void takeNumbers(string &userAmount, string (&numberArray)[11]){
int temp = stoi(userAmount);
for (int i = 0; i < temp; i++){
cout << "Input number #" << i+1 << " ->";
cin >> numberArray[i];
cout << endl;
}
}
void display(string &userAmount, string (&numberArray)[11]){
int temp = stoi(userAmount);
for (int i = 0; i < temp; i++){
cout << numberArray[i];
cout << endl;
}
}
void addNumber(string &userAmount, string (&numberArray)[11]){
}
int main() {
const int MIN_AMOUNT = 2, MAX_AMOUNT = 11, MAX_INPUT = 14;
string userAmount = "0";
string numberInput;
// static array
string numberArray [MAX_AMOUNT];
amountOfNumbers(userAmount, MIN_AMOUNT, MAX_AMOUNT);
takeNumbers(userAmount, numberArray);
display(userAmount, numberArray);
}
I am writing a GPA calculator program, and I want to change the value for a char to a different number.
For example if a user enters the letter a or A the value will be 4. This is what my program looks like. I know how to make it work if I use a switch cases, but I would like to do it this way.
char userInput;
char A, a = 4; // i want to change the value of A, a to 4
char B, b = 3; // i want to change the value of B, b to 3
char C, c = 2; // i want to change the value of C, c to 2
char D, d = 1; // i want to change the value of D, d to 1
char F, f = 0; // i want to change the value of F, f to 0
int count2 = 0;
int count3 = 0;
double gpa;
// the for loop is to make sure program will only run 3 times
for (int i=1; i<4;i++)
{
cout << "Test #" << i << ":" << endl;
cout << endl;
// the do while loop is being used to ensure that the user gets to
// input at least once.
do
{
cout << "Enter a Letter Grade (enter 'X' to exit): ";
cin >> userInput;
// the while loop is only being used for input valiation.
while (userInput!='A' && userInput!='a' && userInput!='B' &&
userInput!='b' && userInput!='C' && userInput!='c' &&
userInput!='D' && userInput!='d' && userInput!='F' &&
userInput!='f' && userInput !='X' && userInput !='x')
{
cout << "\n Invalid letter grade, please try again.\n";
cout << "\n Enter Letter Grade (enter 'X' to exit):";
cin >> userInput;
}
//line number 80 will add the values of the userInput together.
count2+=userInput;
// line 83 is a counter that holds the number of times the loop
// as excuted
count3++;
// line 88 will get a grade point average by dividing count3
// by count2
cout << fixed << showpoint << setprecision(2);
gpa = count2/count3;
} while(userInput !='X' && userInput!='x');
cout << "Total Grade Point: " << count2 << endl;
cout << "GPA: " << gpa << endl;
}
If my question is too vague please let me know so I can clarify.
If you look at ASCII table, you'll see that letters are just numbers.
http://www.asciitable.com/
You can calculate offset using simple subtraction:
'a' - 'a' == 0
'b' - 'a' == 1
'c' - 'a' == 2
and so on. To convert it to GPA grade you can do a simple conversion:
int deltaA = (int)('a' - 'a'); // explicit cast to int is not really needed
int max = 4;
int grade = max - deltaA;
Alternative solution would be to use a map:
std::map<char, int> grades;
grades['a'] = 4;
grades['b'] = 3;
grades['c'] = 2;
...
int score = grades['a']; // score == 4
It would be a good idea to stick with upper or lowercase letters. You can convert them using int std::tolower(int ch) and int std::toupper(int ch) functions. Putting char into int is ok - both are integers and int has wider range and char will fit.
The other way around - not so easy. int has wider range than char and you should check if your int value is in char range before converting back.
A couple of things...
char A, a = 4;
Creates character VARIABLES (storage locations) and assigns the variable a the value of 4. A variable represents a memory location, a place to store information. It is a human readable representation of this storage location. It is not a translation mechanism. The CHARACTER 'a' is a value represented by an ascii code that can be stored in the variable, hex value is 61 or decimal 97. Variable a is not the same thing as the character value 'a'. and storing a decimal 4 into a character variable is setting it to the EOT character.
Your best bet is to use the switch. It works fine.
It's best practice to initialize variables before you use them. Your counters will probably start out as zero, but depending on compilers, they may contain random values. Set them to zero before entering your loops.
Thank you guys for all the help. This is how I solved my problem. I meant to post it a while ago but just forgot.
char userInput;
// the for loop is to make sure program will only run 3 times
for (int i=1; i<4;i++)
{
int count2 = 0;
double count3 = 0.0;
double gpa;
cout << "Test #" << i << ":" << endl;
cout << endl;
// the do while loop is being used to ensure that the user gets to
// input at least once.
do
{
cout << "Enter a Letter Grade (enter 'X' to exit): ";
cin >> userInput;
// the while loop is only being used for input validation.
while (userInput!='A' && userInput!='a' && userInput!='B' &&
userInput!='b' && userInput!='C' && userInput!='c' &&
userInput!='D' && userInput!='d' && userInput!='F' &&
userInput!='f' && userInput !='X' && userInput !='x')
{
cout << "\n Invalid letter grade, please try again.\n";
cout << "\n Enter Letter Grade (enter 'X' to exit):";
cin >> userInput;
}
if(userInput !='X' && userInput !='x')
{
int grade=func(userInput);
// count2 will add the values of the userInput together
count2+=grade;
// count3 is a counter that holds the number of times the loop
// as execute.
count3++;
}
cout << fixed << showpoint << setprecision(2);
// to get the grade point avarage you need to divide count3 by count2
gpa = count3/count2;
} while(userInput !='X' && userInput!='x');
// the next few lines will display the information gathered
cout << endl;
cout << "Total Grade Points: " << count2 << endl;
cout << "GPA: " << gpa << endl;
cout << endl;
cout << endl;
}
return 0;
}
int func(char userInput)
{
// grade is being set to zero so there is a less chance of getting wrong
// data
int grade=0;
// this will make the userInput into a capital letter
userInput=toupper(userInput);
// we are setting value to equal the ascii number of the chosen
// letter
int value=userInput; // if input='A' then value = 65
// by subtracting 69 by the value it will help get us the point value
// we need.
grade=69-value; // gpa=4
// if the number value of grade becomes negative it will assign grade
// to store the number 0
if(grade<0)grade=0;
return grade;
}