Converting an octal number to decimal number using char only - c++

I am new here and new to c++ as well.
I just started my first year at school and I have been given an assignment in which one of the questions is to convert an octal number to a decimal number using Char only.
The task is to create a program that receives chars from the user and where the length of the number is not known in advance. The user should press '\t' in order to start calculating to a decimal number.
I don't really understand how it works.Because if I code a simple algorithm such as:
char ch;
cin<<ch;
cout>>ch>>endl;
and I give it 67, it will print 6 only. That means that it reads every char separately, doesn't it?
Could someone please help me understand it by showing me the algorithm for this problem or explaining to me how char works?
Thanks a lot
Coral

You will get enough info on how to read from stdin char by char.
please go through this link.
http://www.cplusplus.com/forum/articles/6046/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string input = "";
// How to get a string/sentence with spaces
cout << "Please enter a valid sentence (with spaces):\n>";
getline(cin, input);
cout << "You entered: " << input << endl << endl;
// How to get a number.
int myNumber = 0;
while (true) {
cout << "Please enter a valid number: ";
getline(cin, input);
// This code converts from string to number safely.
stringstream myStream(input);
if (myStream >> myNumber)
break;
cout << "Invalid number, please try again" << endl;
}
cout << "You entered: " << myNumber << endl << endl;
// How to get a single char.
char myChar = {0};
while (true) {
cout << "Please enter 1 char: ";
getline(cin, input);
if (input.length() == 1) {
myChar = input[0];
break;
}
cout << "Invalid character, please try again" << endl;
}
cout << "You entered: " << myChar << endl << endl;
cout << "All done. And without using the >> operator" << endl;
return 0;
}

Related

How do you test if an input is a number

I am having trouble determining if an input is a letter or a number.
If I enter anything it always says that it is not a number, what am I doing wrong.
Here is my code:
#include <iostream>
#include <unistd.h>
#include <ctype.h>
using namespace std;
int main()
{
int input = 0;
cout << "Enter a number \n";
cout << "input: ";
cin >> input;
if (isdigit(input)) {
cout << "Your number is: " << input;
}
else {
cout << "This is not a number \n";
}
//wait for ten seconds
usleep(10000000);
}
Since isdigit() expects an ASCII value as its argument, it will return true only if you type in a number between 48 (aka the ASCII code for "0") and 57 (aka the ASCII code for "9"), which isn't what you want.
In order to get the behavior you want, you'll need to read the user's input into a string, and then analyze the contents of the string to see if they reasonably represent an integer or not. Something like this:
#include <iostream>
#include <string>
#include <unistd.h>
#include <ctype.h>
using namespace std;
int main()
{
string inputStr;
cout << "Enter a number \n";
cout << "input: ";
cin >> inputStr;
// Assume a string counts as representing an integer
// if the first character of the string is an ASCII digit.
// (You might also want to accept strings where the
// first character is a + or - symbol and is immediately
// followed by an ASCII digit, but for simplicity I'm
// omitting that logic here)
if ((inputStr.length()>0)&&((isdigit(inputStr[0])))) {
int number = stoi(inputStr);
cout << "Your number is: " << number << endl;
}
else {
cout << "[" << inputStr << "] is not a number" << endl;
}
//wait for ten seconds
usleep(10000000);
}
Agree on Jeremy, I would like to add https://stackoverflow.com/a/5655685/7637661 for reference.
TLDR
#include <iostream>
using namespace std;
int main() {
int input = 0;
cout << "Enter a number \n";
cout << "input: ";
cin >> input;
if(!cin) // or if(cin.fail())
{
// user didn't input a number
cin.clear(); // reset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
// next, request user reinput
cout << "This is not a number " << endl;
}
cout << "Your number is: " << input;
}

Checking a string to match a Char variable

I have written a short program that takes a user input and then checks a string for a match to the users input but I need to add another function that checks make sure that the user input is in the string and if its not to return an error.
Here is my code for reference:
const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,’ ";
int main()
{
char letter; //Variable holding user entered letter
cout << "Please enter letter in the aplhabet:" << endl;
cin >> letter;
cout << "The Position of " << letter << " in the string is: " << ALPHABET.find(letter) << endl;
return 0;
}
I think I ought to add an if/else statement that first checks to see if the input is correct and if it is output the position in the string and if not return and error.
If you wanted to be fancy, you could write your own function. However, string::find() is ok. All you need to check is whether or not the returned index is valid or not.
// Example program
#include <iostream>
#include <string>
using namespace std;
const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,’ ";
int main()
{
char letter; //Variable holding user entered letter
string::size_type index; //Index where char is found in string
cout << "Please enter letter in the aplhabet:" << endl;
cin >> letter;
index = ALPHABET.find(letter);
if (index == string::npos)
cout << "Error, letter not found" << endl;
else
cout << "The Position of " << letter << " in the string is: " << index << endl;
return 0;
}
An if/else statement sounds good. And if that doesn't work, there are other multiple ways that it could.

Using cin.get() to discard unwanted characters from the input stream in c++

I am working on an assignment for my C++ class. The following code is given. The directions explain to enter a six character string and observe the results. When I do this, the second user prompt is passed over and the program ends. I am pretty certain the reason for this is that the first cin.getline() is leaving the extra character(s) in the input stream which is messing up the second cin.getline() occurrence. I am to use cin.get, a loop, or both to prevent the extra string characters from interfering with the second cin.getline() function.
Any tips?
#include <iostream>
using namespace std;
int main()
{
char buffer[6];
cout << "Enter five character string: ";
cin.getline(buffer, 6);
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
cout << "Enter another five character string: ";
cin.getline(buffer, 6);
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
return 0;
}
You are right. The newline character stays in the input buffer after the first input.
After the first read try to insert:
cin.ignore(); // to ignore the newline character
or better still:
//discards all input in the standard input stream up to and including the first newline.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
You will have to #include <limits> header for this.
EDIT:
Although using std::string would be much better, following modified code works:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
char buffer[6];
cout << "Enter five character string: ";
for (int i = 0; i < 5; i++)
cin.get(buffer[i]);
buffer[5] = '\0';
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
cout << "Enter another five character string: ";
for (int i = 0; i < 5; i++)
cin.get(buffer[i]);
buffer[5] = '\0';
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl << endl;
cout << "The string you entered was " << buffer << endl;
return 0;
}

Code to get user input not executing/skipping in C++

In the below code, I'm running into an error when I try to get the user to input their name. My program just skips it over and goes right over to making the function calls without allowing the user to enter their name. Despite the error, my program is compiling. I'm not sure what's going wrong as I wrote that part based off other examples I found on here. Any suggestions?
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
char showMenu();
void getLottoPicks(int[]);
void genWinNums(int[]);
bool noDuplicates(int[]);
const int SIZE = 7;
int main()
{
int userTicket[SIZE] = {0};
int winningNums[SIZE] = {0};
char choice;
string name;
srand(time(NULL));
do
{
choice = showMenu();
if (choice == '1')
{
cout << "Please enter your name: " << endl;
getline(cin, name);
getLottoPicks(userTicket);
genWinNums(winningNums);
for (int i = 0; i < SIZE; i++)
cout << winningNums[i];
}
} while (choice != 'Q' && choice != 'q');
system("PAUSE");
return 0;
}
Added the code for showMenu:
char showMenu()
{
char choice;
cout << "LITTLETON CITY LOTTO MODEL:" << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "Q) Quit Program" << endl;
cout << "Please make a selection: " << endl;
cin >> choice;
return choice;
}
And getLottoPicks (this part is very wrong and I'm still working on it):
void getLottoPicks(int numbers[])
{
cout << "Please enter your 7 lotto number picks between 1 and 40: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << "Selection #" << i + 1 << endl;
cin >> numbers[i];
if (numbers[i] < 1 || numbers[i] > 40)
{
cout << "Please choose a number between 1 and 40: " << endl;
cin >> numbers[i];
}
if (noDuplicates(numbers) == false)
{
do
{
cout << "You already picked this number. Please enter a different number: " << endl;
cin >> numbers[i];
noDuplicates(numbers);
} while (noDuplicates(numbers) == false);
}
}
}
After doing cin >> choice; inside char showMenu(), if a user inputs 1[ENTER], the char consumes 1 character from cin, and the newline stays inside the stream. Then, when the program gets to getline(cin, name);, it notices that there's still something inside cin, and reads it. It's a newline character, so getline gets it and returns. That's why the program is behaving the way it is.
In order to fix it - add cin.ignore(); inside char showMenu(), right after you read the input. cin.ignore() ignores the next character - in our case, the newline char.
And a word of advice - try not to mix getline with operator >>. They work in a slightly different way, and can get you into trouble! Or, at least remember to always ignore() after you get anything from std::cin. It may save you a lot of work.
This fixes the code:
char showMenu()
{
char choice;
cout << "LITTLETON CITY LOTTO MODEL:" << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "Q) Quit Program" << endl;
cout << "Please make a selection: " << endl;
cin >> choice;
cin.ignore();
return choice;
}
from looking at code showMenu function has problem. and it's not returning asccii equivalent of '1' that is: 31 integer. try printing value returned by showmenu. you will get that
UPDATE:
It is because cin in delimited by ' '(whitespace) and getline by '\n' character, so when enter name and press enter cin in showmenu will consume whole string except '\n' from istream and that is read by getline. to see this when it ask for choice enter string like 1 myname (1 whitespace myname)and press ENTER will display name. now cin will read 1 in choice and myname in name by getline.

Invalid input in C++ stream

Consider the following code which takes an integer input and then prints the cin stream state:
#include <iostream>
using namespace std;
int main()
{
int number;
cout<<"Enter a number \n";
cin>>number;
cout<<cin.rdstate()<<endl;
return 0;
}
If the number entered is "zzzz" then the rdstate returns a value of 4.
If the number entered is "10zzzz" then the rdstate returns a value of 0, number has a value of 10, and the input stream has "zzzz" in it.
My question is:
1. Why isn't a input of "10zzzz" treated as an invalid input (atleast one of the failure bits should have been set.)
2. What is an elegant solution to detect and handle this situation.
Thanks!!!
First of all I would like to ask what you are trying to do with:
cout<<cin.rdstate()<<endl;
Read this page for the proper use of rdstate()
http://www.cplusplus.com/reference/iostream/ios/rdstate/
second:
to check wetether the input is either stringtype or integer type you might want to add something extra wich will convert the input string to integer data and will respond with an error message when feeded an invalid input.
therefor this will help you out:
int main() {
string input = "";
// How to get a string/sentence with spaces
cout << "Please enter a valid sentence (with spaces):\n>";
getline(cin, input);
cout << "You entered: " << input << endl << endl;
// How to get a number.
int myNumber = 0;
while (true) {
cout << "Please enter a valid number: ";
getline(cin, input);
// This code converts from string to number safely.
stringstream myStream(input);
if (myStream >> myNumber)
break;
cout << "Invalid number, please try again" << endl;
}
cout << "You entered: " << myNumber << endl << endl;
// How to get a single char.
char myChar = {0};
while (true) {
cout << "Please enter 1 char: ";
getline(cin, input);
if (input.length() == 1) {
myChar = input[0];
break;
}
cout << "Invalid character, please try again" << endl;
}
cout << "You entered: " << myChar << endl << endl;
cout << "All done. And without using the >> operator" << endl;
return 0;
}