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;
}
Related
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;
}
i'm making simple program to show "True" if user input 'z' and show "False" if user input anything else.
However, the problem is when user input more than a character, such as when user input 'zz' the output is
True
Input : True
and when user input such as 'zs' which should be wrong, the output is
True
Input : Wrong
Here's my code
#include <iostream>
using namespace std;
int main()
{
char input;
cout << "Check input" << endl;
while(true){
cout << "Input : ";
cin >> input;
if(input=='z'){
cout << "True" << endl;
} else {
cout << "Wrong" << endl;
}
}
return 0;
}
I wonder if there are ways to prevent this without change variable type to string?
I use CodeBlocks 16.04 (MinGW) with GNU GCC Compiler on Windows 10 x64
You cannot do that by reading single chars. The point is that if the user enters e.g. zz he actually did enter those two chars and these are the chars you are getting when you read from cin.
Just read a std::string as suggested and check only the first character of the string. That's just as simple that what you're doing.
So you probably want this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
cout << "Check input" << endl;
while (true) {
cout << "Input : ";
cin >> input;
if (input.length() > 0 && input[0] == 'z') {
cout << "True" << endl;
}
else {
cout << "Wrong" << endl;
}
}
return 0;
}
Its definitely possible you just have to check the first character and make sure It is the only character entered than flush the buffer to get rid of the rest of the string.
code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char input;
cout << "Check input" << endl;
while (true) {
cout << "Input : ";
cin >> input;
//Check if the input is z and there is only 1 character inputted
if (cin.rdbuf()->in_avail() == 1 && input == 'z') {
cout << "True" << endl;
}
else {
cout << "Wrong" << endl;
}
//Flush the buffer
cin.clear();
cin.ignore(INT_MAX, '\n');
}
return 0;
}
When I enter this code and try to run it, it isn't working when the user selects option 1, to enter some text and a string to search for within their text. It outputs "enter text" and then "enter string to search" immediately after, without giving the user the chance to input some text. What is wrong?
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <algorithm>
using namespace std;
string s1, text;
int rand(int*);
int Array[100];
void sortArray(int[], int);
void showArray(const int [], int);
int main()
{
while (1)
// Menu to prompt user choice
{
char choice[1];
cout << endl;
cout << endl;
cout << "--MENU--" << endl;
cout << "1. Pattern Matching" << endl; // search for string within text
cout << "2. Sorting Techniques" << endl; // generate and then sort 10 random numbers
cout << "Enter your choice: " << endl;
cout << endl;
cin >> choice;
cout << endl;
if (choice[0] == '1') // string search option
{
cout << "Enter text:" << endl; // accept text from user
getline (cin, s1);
cout << "Enter string to search:" << endl; // accept string to search from user
getline (cin, text);
int pos = s1.find(text); // finds position where the string is located within text
if (pos >= 0)
{
cout << "Found '" << text << "'" << " at position " << pos + 1 << "." << endl;
}
else
{
cout << "Did not find text." << endl;
}
}
This is because cin >> choice reads part of the current input line for the choice entered by the user. The first getline() call reads the remaining part of the input line immediately following the choice entered by the user. You need to ignore the rest of the input line after the choice.
cin >> choice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
You will also need to add #include <limits> to the beginning of your code in order to pull in numerical_limits.
It looks as though you are defining some sort of char array for the user response. I would tend to make that a non-zero integer type with an exception if the choice is neither 1 nor 2. There are also some shortcuts for output formatting that reduces lines of code. Also, you would want to include the standard string class to accept the string. Maybe try something like the following:
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <algorithm>
using namespace std;
string s1, text;
int rand(int*);
int Array[100];
void sortArray(int[], int);
void showArray(const int [], int);
int main()
{
while (1)
// Menu to prompt user choice
{
int choice;
cout << "\n--MENU--\n"l;
cout << "1. Pattern Matching\n"; // search for string within text
cout << "2. Sorting Techniques\n"; // generate and then sort 10 random numbers
cout << "Enter your choice:\n";
cin >> choice+"\n";
if (choice == 1 && choice > 0 && choice != 0) // string search option
{
cout << "Enter text:" << endl; // accept text from user
getline (cin, s1);
cout << "Enter string to search:" << endl; // accept string to search from user
getline (cin, text);
int pos = s1.find(text); // finds position where the string is located within text
if (pos >= 0)
{
cout << "Found '" << text << "'" << " at position " << pos + 1 << ".\n";
}
else
{
cout << "Did not find text.\n";
}
}}}
//review3
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
using namespace std;
int number;
int main()
{
cout << "Enter a positive number" << endl;
cin >> number;
while (number < 0)
{
cout << "Enter a positive number" << endl;
}
if (number > 0)
{
cout << "Awesome job!" << endl;
}
return 0;
}
This is my code so far. I started with an else if but if the user entered a negative number the program would simply close. I changed this to a while loop and got stuck in an infinite loop. Before I had an if and else if statement. I need to continue to prompt the user until they enter a positive number in c++.
Your while() loop doesn't continue to prompt for input, that's why you're getting an infinite loop - because number never changes!
You can put the input operation into the while() loop like this:
while (cin >> number && number < 0)
{
cout << "Enter a positive number: " << endl;
}
if (cin)
{
cout << "Awesome job" << endl;
}
Thus, during each iteration of the loop the user will be prompted for input.
We check the state of cin afterwards to make sure that the above loop didn't stop because of invalid input (or no input at all).
#include <iostream>
using namespace std;
int number;
int main()
{
cout << "Enter a positive number" << endl;
cin >> number;
if (number < 0) {
cout << "Enter a positive number" << endl;
}
else {
cout << "Awesome job!" << endl;
}
return 0;
}
You can check if you get number or string here
sure in this case you should get input to string variable. If you want to convert it to integer you can use std::stoi
#include <iostream>
#include <string>
#include <cstring>
int main()
{
while(true)
{
std::cout << "Pleaase enter a positive number." << std::endl;
std::string buf;
int x = -255;
std::cin >> buf;
x = std::atoi(buf.c_str());
if(x > 0)
{
break;
}
}
std::cout << "Awesome Job!" << std::endl;
}
You can also do this snippet . Use #include <ctype.h> or <cctype>
while(1){
cin>>number;
if(number<0 || isalpha(number)) return 0;
cout<<"Awesome Job";
}
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;
}