String to ascii function - c++

I actually wrote a function to convert string into ascii values.
However I managed to confuse my self and don't understand why my own code works.
here it is:
void convertToString()
{
char redo;
int letter;
int length;
do {
cout<< "How long is your word \n";
cin >> length;
cout << "Type in the letter values \n";
for (int x = 0; x < length; x++) {
cin >> letter;
cout << char (letter);
}
cout << "\n To enter another word hit R" << endl;
cin >> redo;
} while (redo == 'R');
}
In the terminal I can type in all the ASCII values I want with out changing line, however I though this would cause a problem, anyways my question is, is hitting the enter button the same as hitting space? if not i dont understand how my code is able to print out the chars since i write it all in one line...Does it assign the interger "letter" a new value everytime there is a space?
Please help/explain

This is to expand a bit on what Igor said in his comment and to give a little example.
As Igor said, istream::operator>>(&int) will read non-whitespace. This means for each call on the operator, it scans along the input stream (what you typed in) for non-whitespace and reads until the next whitespace again. The next call will pick up where you left off. So, entering a space or a newline is exactly the same for this situation where you're taking in an int.
You can verify this with a simple bit of code that scans until EOF:
#include <iostream>
int main()
{
int number;
while (std::cin >> number)
{
std::cout << number << std::endl;
}
return 0;
}
This will wait for user entry to be complete (pressing enter), but print a new line for each integer in your input as separated by whitespace. So "1 2 3 4" will print each of those numbers on separate lines, regardless of if you separate them with spaces, tabs, or newlines.

Related

function CIN gets skipped every time

I wanted to make a small "game" with a little bit of story, but I did some code and I think i did some major mistakes, here's the code
int main() {
char o, z, q, r;
string f, w = "yes", e = "no";
cout << "Hello, summoner!" << endl;
cin >> o;
cout << "You know why you are here, right?" << endl;
cin >> q;
switch ( z ) {
case 'w':
cout << "Ok";
break;
case 'e':
cout << "You are here to fight for your life!";
break;
}
return 0;
}
The second cin, the cin >> q; gets skipped every time I run the code and I don't know what to do.
It may not get skipped. You may be entering more than one characters in 'o', which is not allowed in your case and the second character automatically is stored in variable q.
Try changing the data type of the variables mentioned if you want to enter longer strings in the variables.
The second cin does not get skipped! When you enter "Hi" then std::cin >> o; will read 'H' while 'i' is still left in the stream. Then std::cin >> q; will read that 'i'. You can see the effect here:
#include <iostream>
int main() {
char first,second;
std::cin >> first;
std::cin >> second;
std::cout << first << " " << second;
}
When you type Hi then press enter the output will be
H i
If you want to store more than a single character then do not use char. For elaborated input checking you can use std::getline to read the whole line of user input and then check if it was a single character, a whole word, or something else.
PS: Don't use single letter variable names only. This is confusing and makes your code very hard to read and understand.
PPS: No offense, but don't make assumptions on what your code does. Instead use a debugger to see what actually happens. And try to be more precise on what you provide as input and what happens then. Your interpretation of "cin gets skipped" is off, and you could have seen this by inspecting the values of o and q after both cins.

While loop repeats for every word in a string in C++

I am trying to make a magic 8 ball that provides a random preset answer to any input except "bye". Each time the void function magic8ball() is called, it generates a random number from 0 - 19 and prints a corresponding response to the console.
int main()
{
string question;
cin >> question;
while (question != "bye") {
magic8ball();
cout << "~Ask another question.\n";
cin >> question;
}
return 0;
}
For some reason, if the input for question has more than one word / has whitespace between characters, the loop repeats for each word before asking for input again. I stuck a "cout << question << endl;" in there and it showed each word in the string (as well as a call of magic8ball and "ask another").
e.g
>hi frend
... Ask again later
hi
~Ask another question.
... Don't count on it
frend
~Ask another question.
How do I prevent the while loop from treating the string as a series of words? Why is cin not triggering along with magic8ball() and cout ?
std::cin stops reading when it sees whitespace. Space also counts as a whitespace.
If you want your string to have space, use std::getline()
int main()
{
string question;
std::getline(std::cin, question);
while (question != "bye") {
magic8ball();
cout << "~Ask another question.\n";
std::getline(std::cin, question);
}
return 0;
}

C++: How can I allow user to retry if they accidentally enter more than one character in char variable?

Question: In C++, ow do I make a program throw out an error when a user enters multiple characters for an input requesting a single character? I'd like to have the program re-prompt for a single character, but it just keeps going and entering the multiple characters on later lines.
This is a very simple program I wrote to test out character inputs and their properties to help me with another assignment. I wanted to see how it would react to multi-character inputs.
//Include statements
#include <iostream>
#include <string>
using namespace std;
//main statement
int main ()
{
//name variables
int numChar;
char letterEntry;
string finalWord = "";
//begin entry
cout << "This program will let you enter characters and combine them into a string." << endl;
cout << "First tell us how many characters you want to enter." << endl;
cin >> numChar;
//convert characters to string and add to string variable
int counter = 0;
while (counter<numChar)
{
cout << "Enter a character!" << endl;
cin >> letterEntry;
finalWord = finalWord + string(1, letterEntry);
counter++;
}
//Display final word
cout << "Your word is " << finalWord << endl;
return(0);
}
This is an output that demonstrates my issue.
This program will let you enter characters and combine them into a string.
First tell us how many characters you want to enter.
3
Enter a character!
DOGS
Enter a character!
Enter a character!
Your word is DOG
I want the program to not save anything if the user types in more than one character. I want it to print an error message that says "You entered more than one character, please retry," and lets them try again. Is there a way to do this with type char?
Thanks!

checking for the \n character, but nothing after that

We are working on trying to get a simple program to either say a turtle has laid eggs or not, based on user input.
The turtle starts with 8 eggs and only lays one when the user presses Enter. ('\n').
We have finally got it to work in the sense that if we press Enter, it will say the turtle lays an egg and counts down to 0 eggs left. It will also say that no egg was laid if you type anything else.
The issue we are having is to keep it from returning the 'else' statement multiple times if someone inputs more than one incorrect character we used the cin.ignore command.
However, we questioned what would happen if we only put in cin.ignore(10, '\n'), and the input was more than 10 characters. The answer is that it repeats the 'else' statement of not laying an egg.
Is there a way to just clear the input stream after the first character so the input can be as much as they want, and it will still only return one line (either laid an egg or not) for each input?
Here is the code.
int main()
{
using namespace std;
int eggs = 8;
char input;
while (eggs > 0)
{
cout << "Enter input: ";
cin.get(input);
if (input == '\n')
{
cout << "Raphie laid an egg because you pressed enter.\n";
eggs--;
cout << "She has " << eggs << " left.\n";
}
else
{
cout << "Raphie didn't lay an egg.\n";
cin.ignore(10, '\n');
}
}
return 0;
}
You can use...
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
...to ignore any amount of input before the newline.
Well usually you'd want to either read in lines or single characters. Notice how '\n' fits in both categories.
If you still want (or have) to stick with ignoring characters, you could try ignoring exactly numeric_limits<streamsize>::max(), which is the maximum number of characters in a stream at any given time.
int main()
{
using namespace std;
int eggs = 8;
char input;
while (eggs > 0)
{
cout << "Enter input: ";
cin.get(input);
if (input == '\n')
{
if (eggs > 0)
{
cout << "Raphie laid an egg because you pressed enter.\n";
eggs--;
cout << "She has " << eggs << " left.\n";
}
}
else
{
cout << "Raphie didn't lay an egg.\n";
cin.ignore(10, '\n');
}
}
return 0;
}

How to get two inputs from a same input (C++)

Title probably sounds confusing so first I'll show you my code, I made this simple program to get two input values and multiply them, and another thing, but that's not important, It works correctly:
#include <iostream>
using namespace std;
main()
{
int a,b,c,d,e;
char j = 4;
cout << "Welcome to Momentum Calculator\n\n";
cout << "------------------------------\n";
cout << "Please Enter Mass in KG (if the mass in in grams, put \"9999\" and hit enter): \n\n";
cin >> a;
if (a==9999) {
cout << "\nPlease Enter Mass in grams: \n\n";
cin >> d;
}
else {
d = 0;
}
cout << "\nPlease Enter Velocity \n\n";
cin >> e;
if (d == 0)
{
c = (a*e);
}
else {
c = (e*d)/100;
}
cout << "\nMomentum = " << c;
cin.get();
cin.ignore();
while (j == 4)
{
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
main();
}
}
Now as you can see, my variable is an int (integer) and my problem is If I enter an English letter (a-z) or anything that is not a number will cause it to repeat my program unlimited times at an unlimited speed. I want a string/char to see if my var "a" is a letter or anything but don't know how to. I can do it, however, I want user to input only one time in "a" and mine makes him to enter again. Please Help :)
There is a function called isalpha in ctype library, checks whether your variable is an alphabetic letter so you can do using isalpha function.
Will isdigit or isalpha from standard library help you?
P.S.
1KG contains 1000 grams, so you should divide by 1000, not by 100;
UPDATE:
Seems I understood your question...
You need cin.clear(); before cin.get() and cin.ignore().
Otherwise the these calls won't do anything, as cin is in an error state.
I think you can get a as an String, and see if it contains English letter or not, if it contains, again ask for the input ( you can do it in a while loop ). And when a correct input entered, parse it and find what is it's number.