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!!
Related
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;
}
I have a character array that produces a random array of lowercase letters in the length that the user inputs. my problem is that after the array of random letters is produced the user inputs a pair of charaters(two letters) and my code should check if that pair is in the random array that was produced. it worked fine when it just checked for one letter but when i introduced the second one it does not work.I would appreciate any help.
#include <ctime>
#include <iostream>
#include <cstdlib>
int main() {
std::srand(std::time(NULL));
int i, num;
char letter1, letter2, ch, r;
const char chars[]="abcdefghijklmnopqrstuvwxyz";
std::cout << "How many letters do you want in your string? ";
std::cin >> num;
for (i=0; i<num; i++)
{
ch = chars[rand()%26];
std::cout << ch;
}
std::cout << "\nWhat letter pair would you like to find? ";
std::cin >> letter1 >> letter2;
if ((chars[i] == letter1) && (chars[i+1]==letter2))
std::cout << "It is in your string. ";
else
std::cout << "You do not have " << letter1 << letter2 << " in your string";
}
First, you are not storing your randomly generated chars
for (i=0; i<num; i++)
{
ch = chars[rand()%26];
std::cout << ch;
}
This just writes a random char in ch and displays it on the console with each iteration. You don't store your data, ch just contains the last random char after your loop ends and everything else is lost.
The part where you want to search is double wrong.
if ((chars[i] == letter1) && (chars[i+1]==letter2))
std::cout << "It is in your string. ";
else
std::cout << "You do not have " << letter1 << letter2 << " in your string";
This isn't inside a loop, i is simply always going to be num-1.
The array you are checking is chars which is your const array containing "abcdefghijklmnopqrstuvwxyz". This doesn't contain your randomly generated chars.
Say we have the user input a name that is a string "william" and then the user enters the character that they want to find the index of.
using namespace std;
string name;
char characterToFind;
cout << "Enter a name ";
cin >> name;
cout << "Enter a character to find ";
cin >> characterToFind;
We then want to find the index of the character in the name string array.
for (int j = 0; j < name.length(); j++) {
if (name[j] == characterToFind) {
cout << "char is at index: " << j << endl;
}
}
How do I then check if the inputted character doesnt exist in the name string array? I try to do the following:
if (characterToFind != name.find(characterToFind)) {
cout<< "doesnt exist" << endl;
}
The if statement always seems to be true and runs the code even if the character that was inputted existed in the name string array.
The problem with my approach was that I was doing was that in the if condition i was checking a 's' char vs a index position of an array.
instead, doing:
if (name.find(characterToFind) == std::string::npos) {
cout << "doesnt exist" << endl;
}
this is checking if the character input is equal to a position that doesnt exist! This is true so it tells the user that the character entered does not exist.
I want to create a program which is able to count the characters in a word.
This is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// ask the user to input the word, at least contain 5 characters
do
{
string inputWord = "";
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
// ask the user to input a character
do
{
char searchCh = '0';
cout << "please enter a character from \n" << inputWord;
cin >> searchCh;
}while(searchCh.size()<1 && searchCH.size()>1);
// iterate over the word
for(int i=0;i < (int) inputWord.size(); i++)
{
// get the character
char ch = word.at(i);
// if the character matches the character we're looking for
if(searcCh==ch)
// increment counter
{
counter++; // counter = counter + 1
}
}
// output the number of times character appears
cout << "the word " << word << " contain character " << searchCh << "is" << counter;
return 0;
}
and I always get the error: inputWord was not declared.
What is the cause this error?
You should read about scopes. Variables in c++ have visibility and lifetime in scope, in which the were declared. For instance, inputWord is visible and exists only in the first do-while loop. Move its declaration above loop. Your code has many such errors. Moreover, I do not see, where is counter declared and it should be properly initialized.
You have mixed up a lot of variable names and used variables outside their scope.
Here is a working version of your code with a few debugs:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// ask the user to input the word, at least contain 5 characters
string inputWord = "";
char searchCh = '0';
char ch;
int counter=0;
do
{
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
// ask the user to input a character
cout << "please enter a character from \n" << inputWord;
cin >> searchCh;
// iterate over the word
for(int i=0;i < (int) inputWord.size(); i++)
{
// get the character
ch = inputWord[i];
// if the character matches the character we're looking for
if(searchCh==ch)
// increment counter
counter++; // counter = counter + 1
}
// output the number of times character appears
cout << "the word " << inputWord << " contain character " << searchCh << " is " << counter;
return 0;
}
You declared the inputWord as string, please check your compiler works for that or not because some compilers do not take the specifier "string". Also searchCh, counter and word is also missing from your program. First of all declare these variables properly.
you should define the "inputWord" before start the while loop , like this :
string inputWord = "";
do
{
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
because "inputWord" is inside the loop ,
I've created a program that allows the user to enter 10 grades. I've used a while loop to store grades in the array, but if the user only has 5 grades to input, he can type done to exit the program.
After the loop has finished, it will then calculate and display. the highest grade, lowest grade, and the average grade within the array
Unfortunately, when the user types done, the program will display the rest of the grade lines that were not entered.
Can you help me find out how to stop the while loop from displaying the rest of unentered grades of the loop?
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 10;
int grade[SIZE];
int count = 0;
int lowestGrade;
int highestGrade;
bool done = false;
cout << "This program is limited to entering up to 10 grades." << endl;
while ( grade[count] != done && count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
cin >> grade[count];
count++;
}
//LOWEST GRADE
lowestGrade = grade[0];
for (count = 0; count < SIZE; count++)
if (grade[count] < lowestGrade)
{
lowestGrade = grade[count];
}
//HIGHEST GRADE
highestGrade = grade[0];
for (count = 0; count < SIZE; count++)
{
if (grade[count] > highestGrade)
{
highestGrade = grade[count];
}
}
//AVERAGE GRADE
double total = 0;
double average;
for (int count = 0; count < SIZE; count++)
total += grade[count];
average = (total / SIZE);
cout << endl;
cout << "Your highest grade is: " << highestGrade << endl;
cout << "Your lowest grade is: " << lowestGrade << endl;
cout << "Your average grade is: " << average << endl;
system("pause");
return 0;
}
Here are two problems with your code.
First:
....
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
cin >> grade[count];
count++;
....
The code above will attepmpt to read word "done" into integer variable, producing 0. Not what you want to do!
Second:
...
for (count = 0; count < SIZE; count++)
...
Code above will try to iterate over all possible elements (SIZE). However, you might have enetered less than that! You need to use count calculated in the previous loop as your boundary (and of course, use a different name for control variable in the loop).
There are a couple of things to unpack here.
Basically, the input you are retrieving is a char * and the >> operator is casting that to an int to fit into your array of grades.
Next what you are checking with grade[count] != done is if the integer in "grade" at the id "count" is not equal to the bool false. This will always return true in this case.
For your use case what you want to be checking is if your input is equal to the char * "done"
This cannot be happening in the predicate of the while loop because your grade array stores only int.
Therefore the simplest solution to the problem in my opinion, is to check whether the input is equal to "done".
If it is you want to set the done boolean to true
Otherwise we can try to cast it to an int and store that in the grades array.
Here is the revised loop:
while (!done && count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
string input = "";
cin >> input;
if (input == "done")
{
done = true;
}
else
{
grade[count] = stoi(input);
}
count++;
}
The following is somewhat outside the scope of the question, but an additionnal advantage to using stoi() is that it ignores input that is not a number, which will shield against someone entering invalid input like "potato". This is why I immediately cast the input into a string.
Use another variable to store the amount ofgrades the user entered. You also cannot store a string in your integer array:
std::string input = "";
while(count < SIZE)
{
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
getline(cin, input);
if(input == "done")
break;
try
{
grade[count] = std::stoi(input);
count++;
}
catch(std::invalid_argument)
{
cout << "not a valid number\n";
}
}
int actualsize = count;
and then use this variable to abort your for loops:
for (int i = 0; i < actualsize; i++)
There are two simple ways to solve your problem:
You can read strings instead of integers and in case the read string is "done", break the loop, else, convert the read string to an integer, something as follows:
```
// rest of the code
int total_count = 0;
while (count < SIZE) {
cout << "Enter a grade #" << count + 1 << " or done to quit: ";
string temp;
cin >> temp;
if(temp == "done") {
break;
} else {
grade[count] = stoi(temp);
count++;
total_count = count;
}
}
// rest of the code
```
If you don't want to use strings, then, assuming grades will be non-negative, you can stop reading input when the user types a negative number, say "-1". So, you will need to do something as follows:
```
// rest of the code
int total_count = 0;
while (count < SIZE) {
cout << "Enter a grade #" << count + 1 << " or -1 to quit: ";
int temp;
cin >> temp;
if(temp == -1) {
break;
} else {
grade[count] = temp;
count++;
total_count = count;
}
}
// rest of the code
```
Also, don't forget to replace SIZE by total_count in rest of the loops i.e. the ones computing 'LOWEST GRADE', 'HIGHEST GRADE' and 'AVERAGE GRADE'.
NOTE: You will have to do #include <string> at the top as well, if you use the first option.