Variable hey should be overwritten when I go through the for-loop, so if I don't enter 1, it says "bye", but then if I enter 1 when it goes through the loop, it should say "hello", but instead it's saying "bye".
#include <iostream>
using namespace std;
int main(){
char hey;
for (int n = 0; n <= 10; n++){
cout << "enter 1" << endl;
cin >> hey;
if (hey == 1)
cout << "hello\n";
else
cout << "bye";
}
}
The character '1' with ASCII numer 49 is different from the number 1.
Use
if (hey == '1')
If you want to compare something to the character a, you´ll have to use 'a' too. It´s the same here.
The problem is hey is of type char. Therefore the input read from the console is interpreted as a char. You can either make the comparison if (hey == '1') or change the type of hey to something such as int.
If the user enters '1', char will be the character code for '1', which is 49.
https://msdn.microsoft.com/en-us/library/60ecse8t(v=vs.80).aspx
You could change your code to either
if (hey == '1')
or
if (hey == 49)
The title for this post is incorrect, by the way.
Change char hey to int hey. It will work as you expect.
You are comparing Ascii character value to Integer . Ascii value of 1 is 49
Related
I've created a guessing game where you have to guess randomly generated number in range from 1 to 100. I also managed to restrict a user if they enter a number that is out of the range, and requires new input. The problem is when you accidentally enter letters or symbols. Then it enters an infinite loop. I tried:
while(x<1 || x>100 || cin.fail())//1. tried to test if input failed (AFAIU it checks if input is expected type and if it is not it fails)
while(x<1 || x>100 || x>='a' && x<='z' || x>='A' && <='Z') // 2. tried to test for letters at least
while(x<1 || x>100 x!=(int)x)//3. to test if it is not integer
{ cout<<"Out of range";
cin>>x;
}
For one solution, you could try and use isdigit. This checks to see if input is actually a number. So you can do something like:
if(!(isdigit(x))){
cout << "That is not an acceptable entry. \n";
continue;
}
EDIT: I should say, that after researching this, I realized that for isdigit to work, the entry needs to be a char. However, this can still work if you convert the char into an int after it discovers that it's an int. Example:
if(!(isdigit(x))){
cout << "That is not an acceptable entry. \n";
continue;
}
else{
int y = x - '0';
}
That int y = x - '0' might seem odd; but it's there because you have to convert the char to an int, and according to the ASCII coding, to do so, you subtract the character '0' from the desired number. You can see that here: Convert char to int in C and C++
I'm supposed to make a program that counts the number of people in each age group:
0-16 (including 16) is infant
16-29 is young
29-55 is middle
55-75 is old
75+ is really old
The intervals are closed to the left and open to the right.
I wrote a program that compiles, but does not give me the correct values. I'm new at coding so can anyone point me in the right direction? Here is what I have:
#include <iostream>
using namespace std;
main()
{
int countinfant, countyoung, countmiddle, countold, countreallyold;
char age;
countinfant=0;
countyoung=0;
countmiddle=0;
countold=0;
countreallyold=0;
cout<< "Please Enter Ages. To end, enter *\n";
cin.get(age);
while (age>0 && age != '*')
{
if (age>=0 && age<=16) countinfant = countinfant + 1;
if (age>16 && age<=29) countyoung = countyoung + 1;
if (age>29 && age<=55) countmiddle = countmiddle + 1;
if (age>55 && age<=75) countold = countold + 1;
if (age>75 && age>=76) countreallyold = countreallyold + 1;
cin.get(age);
}
cout<< "\n The Number of Infant's Are: " << countinfant;
cout<< "\n The Number of Young's Are: " << countyoung;
cout<< "\n The Number of Middle's Are: " <<countmiddle;
cout<< "\n The Number of old's Are: " <<countold;
cout<< "\n The Number of Really Old's Are: " <<countreallyold;
cout<<endl;
return 0;
}
Actually your problem is very easy to figure out once I looked closer at the code.
The get function of input streams read a single character and not numbers. So if you enter the character 5 as input it will be read and stored in age as a character, and if the encoding used on your system is ASCII encoding (which is the most common these days) then the value for the character '5' is the integer 53.
You then proceed to use the character you have read as an integer, which as it is encoded will give you the wrong results.
To get the correct values you need to read an integer, however since you want to check for the asterisk to end the input you can't use normal integer input with the >> operator, which is why you used get I guess. The solution is to use strings and check the string for the asterisk, and if not an asterisk convert the string to an integer.
Something like
std::string input;
while (std::cin >> input && input != "*")
{
int age = std::stoi(input);
...
}
It does not work because you declared age as a char. The program reads the input as a char, so if you enter 0, the value in age will be the ASCII code of the character 0, which is 48 (0x30). You need to declare it as int age; and for the exit condition simply enter a negative value, e.g. -1, don't use the '*'.
I am new to C++ and coming from a C# / Java background I feel like I am kind of spoilt.
What I am trying to achieve here is to get the data input by the user as byte (unsigned char) using cin.
#include <iostream>
using namespace std;
typedef unsigned char byte;
int main()
{
byte num = 0;
char exitKey = '0';
cout << "Type in a number between 0 and 255.\n";
cin >> num;
cout << "\nYour number multiplied by 2 is:\n" << (num * 2);
cin >> exitKey;
return 0;
}
The value returned is the ASCII decimal value of the character I typed in. How can I get the actual value, treating the value as a number?
Help is appreciated. Thanks.
It doesn't matter what type-aliases you use, when reading using cin >> a character is always a character, and will be read as a character.
The value you are getting is the ASCII code for the character '1'.
If you want to read it as a number, then use a proper numeric datatype, like int.
Since you are using char datatype here. The 1 value entered here is considered as character and ASCII value of 1 (49) is getting stored and 49 * 2 = 98 is getting printed.
Instead of char use int as datatype.
>The character 'b' is char('a'+1),'c' is char('a'+2),etc. Use a loop to write out a table of characters with their corresponding integer values.
I cannot finish this exercise because of this error.
error: lvalue required as increment operand
for(char a='a'; a<24; ++a)
{
cout<<char('a'++);
}
The loop body will never execute with the controlling expression a < 24 because you have initialized variable a with character a and all printable characters are not less than ASCII value 32.
Try this:
for(char a='a'; a < 'a' + 24; ++a)
{
cout << a;
}
I think you would be less confused if you named your variable letter instead of a, because it only represents the letter 'a' at the very beginning.
for(char letter='a'; letter<24; ++letter)
{
cout<<char('a'++);
}
I'm going to assume you actually want to print out the entire alphabet, not just the first 24 letters.
It looks from here like you tried to do a mix of two possible approaches. In the first approach, you increment a char from a to z with each iteration of the for loop and print it out each time. In the second approach, you increment some offset from 0 to 25 and print out 'a' + offset.
You mix these two approaches up in the first line. You're starting the loop with letter set to 'a', which you do not know the numerical value of. You then compare letter to see if it is less than 24. Well in any ASCII-compatible character set, the character 'a' has value 97, so this condition will never pass.
You then misuse ++ on the cout line. The ++ operator attempts to modify its operand, yet 'a' is a literal and so cannot be modified. Have a look at what your assignment told you. You can do 'a' + 1 to get 'b', for example, so this assumes you have an offset (which you don't with your current approach).
So to repeat, you have two options. First: keep letter as a char starting at 'a' and fix the condition so that it checks if letter is less than or equal to the value of 'z' and then just print out letter. Second: change letter to offset and start it off at 0 and increment it while it is less than 26, and then print out 'a' + offset.
Note, however, that both of these approaches assume that the letters have consecutive values in the execution character set. This is not necessarily true.
The ++ operator is a "hidden assignment" (the operand's value is changed by it). But you can only assign to variables, which 'a' is not.
I know this has been closed for a while but since the exercise was about while loops and not for loops, I thought I would offer my solution. I'm just going through the book myself and someone in the future might stumble over this.
int i = 0;
char n = 'a'; // this will list the alphabet
int conv = 0;
conv = n; // this converts the alphabet into integer
while (i < 26) { // starts from 0 and goes to 25
cout << char(n + i) << '\t' << conv + i << '\n';
++i;
}
You may use the following: (http://ideone.com/akwGhl)
#include <iostream>
int main()
{
for (char c = 'a'; c <= 'z'; ++c) {
std::cout << "letter " << c << " has value " << int(c) << std::endl;
}
return 0;
}
hey through troubleshooting i obtained a sample that worked , i have yet to perfectly understand how my code works but as the solutions that were proposed to me here seemed too technical for my level i figured that i should publish mine
#include"header files . h"//i use the libraries given in the book
int main () {
char a ='a';
int i = 0 ;
while (i <= 25)//for (i = 0 ; i <= 25 ; i++)
//for those who used for
{
cout << a << '\t' << 'a' + i << endl;
a += 1; // augments the character value of a to b ... then to z
i++; // augments the value of i allowing us thus to make the augmentation,if you are using the for structure do not put I in your code
}
}
I am very new to programming, so I apologize if this question seems absurdly simple. I am working on some extra questions in the current chapter of my C++ book. I have actually found a correct answer to the problem, but while doing so, I ran into a situation that is driving me crazy because I can't figure out WHY one particular solution works and another one doesn't.
So, the problem asks to print the ASCII values between 32 and 127 in a few rows with 16 characters per row. The solution I have come to (that works correctly) is this:
#include <iostream>
using namespace std;
int main()
{
char letter;
int count = 0;
for (letter = 32; letter < 127; letter++, count++)
{
if (count == 16)
{
cout << endl;
count = 0;
}
cout << letter << " ";
}
cout << endl;
return 0;
}
Again, the above code runs fine and does what I want it to. The difficulty lies in something I tried before this. I attempted to do the same problem with a nested while loop, like so:
#include <iostream>
using namespace std;
int main()
{
char letter = 32;
int count;
while (letter < 127)
{
count = 0;
while (count < 16)
{
cout << letter << " ";
letter++;
count++;
}
cout << endl;
}
cout << endl;
return 0;
}
This while loop just runs infinitely and also spits out some garbage after the ASCII characters I want, and I can't figure out why. What's even weirder is if I change the variable 'letter' in the code with while loops to an int instead of a char, it runs exactly the way I want it to and terminates when it should, just displaying the actual numbers instead of the ASCII values.
It's only when 'letter' is a char that I get an infinite loop. I'm sure it's something really simple, and I might just be too tired to see it right now, but any help/hints would be much appreciated! Even though I technically got the answer, it's driving me crazy that I don't know WHY the second answer fails so horribly.
Thanks in advance.
The answer is simple, true enough. Here is what happens - (signed)char can have values in the range [-128, 127] in the inner loop after you output the row up to 112, you increment count with another 16 and therefor you also increment letter with 16, this makes letter equal to 112 + 16 = 128, which due to the range of signed char is actually overflowing and becomes -128. So after this execution of the inner loop the condition of the outer loop still holds: -128 < 127. That is also why you get weird chars - these will be the values between -128 and 32.
How to fix the problem? Change the check in the inner loop:
while (count < 16 && letter < 127)
The inner while loop exits when letter == 48, 64, ..., 128. But as it is a (signed) char, 128 is interpreted as -128 and the outer loop will not terminate.
Change the inner loop to
while (count < 16 && letter < 127)
to get the same behavior as in your first example.
Or change letter to int, if it's OK to print all characters including 127:
int letter = 32;
...
cout << (char)letter << " ";
Try this code :
#include <iostream>
using namespace std;
int main()
{
int letter;
for (letter = 32; letter < 128; ++letter)
{
if (letter != 32 && letter % 16 == 0)
cout << endl;
cout << (char)letter << ' ';
}
}