Code won't cin/ uninitialized local variable - c++

So far my only problem with this code is that C won't initialize. I know that if I make degree_type == "C" it won't compile because I can't turn an int into a character. What's exactly wrong with this code?
#include <iostream>
using namespace std;
int main()
{
char C;
double degree;
int degree_type;
cout << "What's the Degree type?: ";
cin >> degree_type;
if (degree_type == C)
{
cout << "What's the Temperature:? ";
cin >> degree;
cout << "Your Degrees in Celsius is, " << 9 / 5 * degree + 32 << " degrees fahrenheit." << endl;
}
else
{
cout << "What's the Temperature:? ";
cin >> degree;
cout << "Your Degrees in Fahrenhait is, " << (degree - 32) * 5 / 9 << " degrees Celsius." << endl;
}
return 0;
}

You are (or were, before you changed your question) using cin to read a character. When you read one character, the next character (the Enter keypress) remains in the input buffer waiting to be read. The next time you read from cin (to get the temperature), it will immediately see the Enter keypress from the previous input and not let you type anything.
Use getline instead:
std::string str;
std::getline(std::cin, str);
degree_type = str.at(0);
Once you have done that, the test degree_type = C does not do what you think it does for two reasons:
The single equals = is assignment. For comparison, use ==.
The C is the name of a variable. For the character C, use 'C'.

Related

char + int to change the char value

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;
}

Program akes only 1 alphabet input and exits while leaving remaining code unexecuted, why?

when user input a character and press enters to take next input, output window asks to press any key and exit, please help me out to get remaining code working,
Here is the code
char r, R;
char c;
int channels;
int resedential()
{
// float channelscost = costperchannel*channels;
// float Bill = channelscost+processingfee+basiccost;
// cout << "Dear Customer Here is Your Bill" <<" "<<Bill<<endl;
}
int main()
{
cout << " Enter Customer Type" << " " << endl;
cin >> c;
if( c == r || R )
{
cout << " Enter Customer Type" << " " << endl;
cin >> c;
}
}
One thing I recognise, is that your if statement doesn't do what you think it does. Right now you aren't checking if c is equal to R.
Fixed Code:
if(c == r || c == R)
{
cout << "Enter Customer Type " << endl;
cin >> c;
}
Also check that there are actual values in r and R. So it doesn't compare to a constant (char(0)) – ASCII code NUL, resulting from default initialization of file-scoped variables to zero.
Example:
char r = 'A';
char R = 'B';

So I'm having trouble understanding files in C++

I just started learning files and I understand how to set it up and get it to work. I have to write this program where I have to allow the user to enter some information and have the user also update and adjust any data, using binary.
So I can write up until the point where the user can write to and read from the file. But I don't know how to let the user adjust data or add data.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class client {
public:
string name;
int balance;
string id;
};
int main()
{
int ans;
int x;
string nameIn;
string adjName;
client client1;
ofstream out("client1.dat", ios::binary);
cout << "\nDo you want to add information or update info" << endl;
cin >> ans;
if (ans == 1)
{
cout << "\nPlease enter the name of your client" << endl;
cin >> nameIn;
x = nameIn.length();
if (x <= 10)
{
for (int i; i < 10; i++)
{
adjName[i] = nameIn[i];
}
}
else
{
for (int i = x; i < 10; i++)
{
adjName[i] = ' ';
}
}
client1.name = adjName;
cout << "\nPlease enter the balance of your client" << endl;
cin >> client1.balance;
cout << "\nPlease enter the id of your client" << endl;
cin >> client1.id;
cout << "\nThe name of your client is " << endl << client1.name
<< endl << "\nThe balance of your client is " << endl
<< client1.balance << endl << "\nThe id of your client is "
<< endl << client1.id;
out.write(reinterpret_cast<const char*> (&client1), sizeof(client));
}
/*
else if (ans == 2)
{
string answer, newName,line;
cout << "\nWhat name do you want to update? " << endl;
cin >> answer;
cout << "\nWhat is the new name?" << endl;
cin >> newName;
if (out)
}
*/
system("pause");
return 0;
}
so the name needs to be only 10 characters long, so that we can adjust/update it. It compiles and runs, but every time the compiler gets to the part where it checks the name length, it freaks out and says "debug assertion failed"
string subscript out of range.
Also a thing about this code-- if i run it without the bits where you adjust the name to a certain array length, the program runs, and stores everything nicely. But when I try to read back the .dat, it reads it back but exits with an access violation, forcing me to manually stop the debugging. What am I doing wrong?
this is the code for reading the file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class client {
public:
string name;
int balance;
string id;
};
int main()
{
client client1;
char ans;
cout << "\nDo you want to view the information about your client?"
<< endl;
cin >> ans;
ifstream in("client1.dat", ios::binary);
if (ans == 'y' || ans == 'Y')
{
in.read(reinterpret_cast<char*> (&client1), sizeof(client));
cout << "The name is " << endl << client1.name << endl
<< "The balance is " << endl << client1.balance << endl
<< "The id is " << endl << client1.id << endl;
}
system("pause");
return 0;
}
As for the 1st part:
for (int i; i < 10; i++)
// ^
misses to initialize i to zero. Also what if the input was smaller than 10 characters? You're going to access the std::string out of bounds. You should replace the if/else and loops with simply
adjName = nameIn;
while(adjName.length() <= 10) {
adjName += ' ';
}
to get rid of the debug assertion.
For the 2nd part of the question, as already mentioned in the comments you cannot do this with a structure containing classes like std::string.
The reinterpret_cast<char*> (&client1) just obfuscates that std::string uses a pointer to the dynamically allocated character data internally, and that cannot be restored meaningfully when reading the stored data back later (hence the access violation you get).
A viable way might be to use something like
struct client {
char name[11];
int balance;
char id[5];
};
As I guess you need to do this for a homework exercise, and for this purpose that would probably be sufficient.
But you quickly can see the drawbacks, that the character data needs to be fixed in size and you cannot have arbitrary length strings. I never would use such for production ready code.
Another pitfall (as also mentioned) is, that int isn't represented in the same way (order of bytes used, i.e. endianess) in the same way for different CPU architectures. So the binary file can't be used portably with different computers.
The simplest solution is not to use a binary file, but a text formatted file and overload the std::ostream& operator<<(std::ostream&, const client&) and std::istream& operator>>(std::istream&, client&) output/input operators.
Or use some 3rd party library like boost::serialization or google protocol buffers, that supports de-/serialization to binary files.

Can't compare string with while and if statements

I'm trying to create a command menu where the user will be able to perform as many commands as he/she wants until pressing "q" which will end the loop. I think I have everything I need to do this except I realized mid-way that my professor asked to use string. When I included string into the program, I began to get error messages saying "could not convert string to bool" wherever there was a while or if statement. What can I do to fix this problem and get my program working. Thanks in advance.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char option;
char number=0;
string s;
string n;
string p;
string q;
char number2;
cout << " Please enter a number: "<< endl;
cin >> number;
do {
cout << " Please enter a command: " << endl;
cout << " s- square the number " << endl;
cout << " n- add the number and (number +1) " << endl;
cout << " p- add the number and (number -1) " << endl;
cout << " q- quit" << endl;
cin >> option;
if (option=s) {
s= number*number;
cout << "Square of this number is : " << s;
}
else if ( option=n){
number2= number+1;
n= number+number2;
cout << "Sum of" << number << "+" << number2 << "is: " << n;
}
else if (option=p) {
number2= number-1;
p= number+number2;
cout << "Sum of" << number << "+" << number2 << "is" << p;
}
else if (option=q)
cout << "Terminating Program";
} while(option);
return 0;
}
you're assigning in the if and else if rather than comparing.
if (option=s) {
should be
if (option=='s') {
note the double =
Also, you need to put single quotes (') around the character choice.
It's a common mistake that even experienced developers make.
These declarations
char number=0;
string s;
string n;
string p;
string q;
char number2;
should all be int
int number=0;
int s;
int n;
int p;
int q;
int number2;
Let me answer as if I were who will evaluate your homework. You have several issues here:
You are asked to use string. Avoid the use of char and string together.
char option; // professor asked to use string: (-1) point
string option; // ok
When you use a single =, like in option="a", you are assigning the value "a" to the variable option. But in the if-else statements you want to compare, so you should use the == comparison operator. Also, you can't compare a char with a string.
if(option = "a") // error: expression must have bool type: (-2) points
if(option == 'a') // error: no operator "==" matches std::string == char; (-2) points
if(option == "a") // ok
You use while(option), but option is declared as a char, not as a bool. Replace this line to while(option!="q") to finish when you enter q.
while(option); // error: expression must have bool type; (-2) points
while(option != "q"); // GOOD!
Also, your program will finish when you scape from the while-statement; so, try to put the "Terminating Program" message after this.
You do not need to declare such many variables (s, n, p, q, number2). Try to use temporary variables inside each scope, for example:
if (option=="s")
{
cout << "Square of this number is : " << number*number << endl;
}
else if ( option=="n")
{
int number2= number+1;
cout << "Sum of " << number << "+" << number2 << " is : " << number+number2 << endl;
}
In the form you write this code, every time you type a new option you will obtain an output like:
Sum of 10+11 is : 21 Please enter a command:
This is ugly to me (-1 point). Try to put a newline (<< endl;) after every cout lines.
Finally, what if I type any other letter not listed in the menu? I would expect a message like Enter a valid option (-1 point).

Currency Conversion Program

I'm working on a currency converter program that converts the old system of British pounds, Shillings, and pence, into their new system, which is a type of Decimal Pound. Where 100 pence equals a pound. Here is the code for the program
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
int calcNum(int pound, int shilling, int pence)
{
pence = pound*240 + shilling*12 + pence;
return pence;
}
int calcNew(int total_pence, double dec_pound)
{
dec_pound = total_pence / 240;
return dec_pound;
}
int main()
{
int pence;
int shilling;
int pound;
const int OLD_POUND = 240;
const int OLD_SHILLING = 12;
double total_pence;
double dec_pound = 0;
double deci_pound;
cout << "Please Enter the Amount of old pounds: ";
cin >> pound;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old shillings: ";
cin >> shilling;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old pence: ";
cin >> pence;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);
cout << (5, "\n");
cout << "The total amount in decimal pounds is: ";
cout << setprecision(2) << "\x9c" << deci_pound;
_getch();
return 0;
}
When I run this program however, I'm having a bit of a problem. No matter what the number input is, it always says 0 pounds. Just to make sure that the setprecision function at the end wasn't interfering with the code, I had originally set a cout statement with a _getch() after the two functions to show how much deci_pound came out to be calculated to, and once again, it came out as zero. So my issue seems to be somewhere in the functions running the calculations. If someone could help me with this, I would really appreciate it.
Your calcNew(...) function returns an int, make it return a double. Right now it casts to int which involves stripping the decimals.
In your code, dec_pound is set equal to zero, and you're deci_pound = calcNew(dec_pound, total_pence), which divides 0 by 240 = 0.
The order of the parameters when you call both functions is wrong. Your functions are declared and implemented as:
int calcNum(int pound, int shilling, int pence);
int calcNew(int total_pence, double dec_pound);
And then you call them like this:
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);