I'd like to start by saying I am very new to this, so please forgive me if there is a relatively trivial solution to this. I learned here, that we can do a while(std::cin>>inputs){} loop to repeatedly do what we want to, but I can't seem to figure out how to get this program to terminate if you input a completely empty input (hitting enter without putting in any information). I will include my code below, other than this, it works just how i want it to. It's a simple Caesar Cipher. It properly terminates when an invalid input is given, for example, d 15 (this is backwards from what is requested), but entering no input at all, by just hitting enter, doesn't terminate the program. Thank you in advance <3.
#include <iostream>
std::string caesarencrypt(std::string ptext, int shift){
std::string ctext= "";
for(int i=0;i<ptext.length();i++){
if(islower(ptext[i])){
ptext[i]=toupper(ptext[i]);
}; /* turns everything into uppercase letters, which ASCII vary from 65 to 65+26=91 */
ctext += char( int( ptext[i]+shift-65 )%26 +65); /* take each letter, add the shift, subtract the value that makes it ASCII (65), take mod 26, then add the ASCII value again */
}
return ctext;
}
/* to decrypt, set shift=-shift */
int main(){
int shiftval;
std::string ptxt;
std::cout<< "Please input the shift value, then the plaintext, seperated by a space"<<std::endl;
while(std::cin>>shiftval>>ptxt){
std::cout << "Plaintext:" << ptxt <<"\n";
std::cout <<"Ciphertext:" << caesarencrypt(ptxt,shiftval)<<std::endl;
}
return 0;
}
For an even simpler program demonstrating the problem, you may observe the same behavior in the following Celsius to Fahrenheit conversion program.
// F to C temperature conversion, 1/31/19 TJMELKA
#include <iostream>
int main() {
double far;
int cel;
std::cout << "deg(F) to deg(C) conversion" << std::endl;
while(std::cin >> far){
cel=0.555556*(far-32);
std::cout << "The temperature in Celsius is, with the decimals truncated: " << cel << std::endl;
}
return 0;
}