Testing if a string is a number or character [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to determine if a string is a number with C++?
I have written a very simple calculator program in C++. Here it is:
#include <iostream>
#include <string>
using namespace std;
int main()
{
double num1;
double num2;
string op;
double num3;
int x;
bool y = false;
do
{
cout<<"Press t to terminate the application"<<endl;
cout<<"Enter the first number"<<endl;
cin>>num1;
cout<<"Enter the operator"<<endl;
cin>>op;
cout<<"Enter the next number"<<endl;
cin>>num2;
if(op=="/"&&num2==0)
{
cout<<"You are attempting to divide by 0. This is impossible and causes the destruction of the universe. However, the answer is infinity"<<endl;
y = true;
}
if(y==false)
{
if(op=="+") {
num3 = num1+num2;
}
else if(op=="-") {
num3 = num1-num2;
}
else if(op=="*"||op=="x"||op=="X") {
num3 = num1*num2;
}
else {
num3 = num1/num2;
}
cout<<endl;
cout<<endl;
cout<<"Answer:"<<num3<<endl<<endl;
}
} while(x!=12);
return 0;
}
As you can see, I want to allow people to terminate the application by pressing 't'. This obviously won't work because cin will try and assign a letter to a double (if I do press 't' the application crashes). I am planning to use strings instead to get the input, but how would I test if the string is a letter or a number?

#include <cctype>
and use isalhpa(), isdigit(), isalnum() on string contents?

Here is sample and working code, just change it so it suits your needs
#include <iostream>
#include <string>
#include <cctype>
#include <stdlib.h>
using namespace std;
bool isNum(char *s) {
int i = 0, flag;
while(s[i]){
//if there is a letter in a string then string is not a number
if(isalpha(s[i])){
flag = 0;
break;
}
else flag = 1;
i++;
}
if (flag == 1) return true;
else return false;
}
int main(){
char stingnum1[80], stringnum2[80];
double doublenum1, doublenum2;
cin>>stingnum1>>stringnum2;
if(isNum(stingnum1) && isNum(stringnum2)){
doublenum1 = atof(stingnum1);
doublenum2 = atof(stringnum2);
cout<<doublenum1 + doublenum2 << endl;
}
else cout<<"error";
return 0;
}

You can input into a string, and then use the following function:
int atoi ( const char * str );
If the string is numerical it will translate it into an integer.
If the string isn't numerical it will return 0: in which case you can check only the first character of the string, if its a zero then consider the input as a 0. If the first character isn't a zero consider the string as not numeric.

Well if you only check for 't' you can do it stupid and easy way.
if(stringnum1== 't' || stringnum2== 't') {
//terminate
}
else {
doublenum1 = atof(stringnum1)
doublenum2 = atof(stringnum1)
// your math operations
}
Better way would be:
if(isalhpa(stringnum1) || isalpha(stringnum2)){
//terminate
}
else {
doublenum1 = atof(stringnum1)
doublenum2 = atof(stringnum2)
// your math operations
}
P.S.
if you want to test string and not char, here is sample: link the best way would be to make function to test if given string is number or not if it is number return true, else return false (or other way around)

Related

error "invalid conversion from 'const char*' to 'char' [-fpermissive]" in c++ [duplicate]

This question already has answers here:
Single quotes vs. double quotes in C or C++
(15 answers)
Closed 1 year ago.
I'm having a problem with my code. I'm trying to make a program that converts non integer numbers into binary. It returns an error in line 21 saying "invalid conversion from 'const char*' to 'char' [-fpermissive]".
What does this mean and how can I solve it?
#include <iostream>
#include <string>
using namespace std;
int main(){
string number;
cout<<"Insert number";
cin>>number;
int continue = 0, integer;
bool first = false;
while(continue >= 0){
if(primo == false){
integer = number[continue];
first = true;
continue++;
}
else{
char dot = "."; //line 21
char comma = ",";
char check = number[continue];
if((check == comma) or (check == dot)){
continue = -1;
}
else{
int encapsulation = number[continue]
integer = (integer*10)+encapsulation;
continue++;
}
}
}
cout<<integer;
return 0;
}
A few mistakes:
continue is a keyword. I renamed it to cont
Double quotes "." is for strings. Chars constants are surrounded by single quotes as '.'.
#include <iostream>
#include <string>
using namespace std;
int main(){
string number;
cout<<"Insert number";
cin>>number;
int cont = 0;
int integer;
bool first = false;
bool primo = false;
while(cont >= 0){
if(primo == false){
integer = number[cont];
first = true;
cont++;
}
else{
char dot = '.'; //line 21
char comma = '.';
char check = number[cont];
if((check == comma) or (check == dot)){
cont = -1;
}
else{
int encapsulation = number[cont];
integer = (integer*10)+encapsulation;
cont++;
}
}
}
cout<<integer;
return 0;
}
Godbolt: https://godbolt.org/z/Tvz3MKxx7

Check if every string in a set contains equal number of 'a' and 'b' okay I tried again will some one work something out now?

Will some one explain or make a program in c++ of this for me? Got assignment but don't know how to do it.
Question: You are given a set of strings which contain only as and bs, your program should be able to check whether each string has the same number of as and bs in it or not.
e.g. The program will respond true if it get {ab, aabb, aaabbbb, bbbaaa} and say false when it gets {aab, bbba, aaabbbb}
Solve it using stack
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
int count1 = 0;
int count2 = 0;
bool isInLanguageL (string w);
int main()
{
string input;
cout << "Input any string; ";
getline(cin,input);
if (input.length() % 2 != 0)
cout <<"Pattern entered does not match the language ";
else
isInLanguageL(input);
return 0;
}
bool isInLanguageL (string w)
{
stack<string> word1, word2;
string a, b;
for (unsigned i = 0; i < w.length()/2; i++)
{
a = w.at(i);
word1.push(a);
}
reverse(w.begin(), w.end());
for (unsigned i = 0; i < w.length()/2; i++)
{
b = w.at(i);
word2.push(b);
}
while(!word1.empty() && !word2.empty())
{
word1.pop();
count1 = count1++;
word2.pop();
count2 = count2++;
}
if(count1 == count2)
return true;
else
return false;
}
This solution is using stack, please refer to the comments written in the code. If you have any doubt you can comment them.
Code:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
void checkString(string s) {
if (s.size() % 2 != 0) {
cout << "Doesn't satisfy the conditon\n";
return;
}
stack<char> st;
int n = s.size();
for (int i = 0; i < n; ++i) {
/*
case - 1 : If the stack is empty you can directly push the current character into the stack
case - 2 : If there are elements present in the stack, then if the current character is equal to the top character on the stack then we can push the current character
beacuse we didn't find any new character to match them.
*/
if (st.empty() || (st.top() == s[i])) {
st.push(s[i]);
}
/*
case-3 : If the stack is not emtpy and current character is different from the top character on the stack then we found a match like a-b (OR) b-a, so then we will
remove the top element from the stack and move to next character of the string
*/
else if (st.top() != s[i]) {
st.pop();
}
}
/*
case - 1 : After iterating through all the characters in the string, if we find the stack is emtpy then we can say all characters are not matched
case - 2 : If stack is emtpy, then that means all the characters are matched.
*/
(st.empty()) ? (cout << "Yes, satisfies the conditon\n") : (cout << "Doesn't satisfy the conditon\n");
}
int main() {
string s = "";
cin >> s;
checkString(s);
return 0;
}
Your solution has a number of mistakes that you should probably solve by using a debugger. Here's a reference.
This solution doesn't use a stack as you asked for, but you can write this function that uses algorithms to solve your problem:
namespace rs = std::ranges;
bool all_equal_as_and_bs(auto const & strings)
{
return rs::all_of(strings, [](auto const & string)
{
return rs::count(string, 'a') == rs::count(string, 'b');
});
}
And use it like this:
all_equal_as_and_bs(std::vector<std::string>{"ab", "aabb", "aaabbb", "bbbaaa"}); // true
all_equal_as_and_bs(std::vector<std::string>{"aab", "bba", "aaabbbb", "bbbaaa"}); // false

Check input string to see if it is a number in C++ [duplicate]

This question already has answers here:
How to check if input is numeric in C++
(8 answers)
Closed 6 years ago.
I'm new to C++,
can I ask is there a way to check if a input string is a number?
If it is a number, change it to integer.
I know we can use either atoi or stoi.
But how can we create it in a function?
Construct a std::istringstream from the std::string.
Extract a number from it. If extraction is successful, use the number. If not, move on to the next thing.
std::string s = "123";
std::istringstream str(s);
int n;
if ( str >> n )
{
// Extraction is successful.
// Use n.
}
Further Enahncements
To make your program more robust, you can add a further check to make sure that:
"123FAST" is not treated as an integer.
"123.56" is not treated as an integer.
"123.56xyz" is not treated as an integer.
std::string s = "123";
std::istringstream str(s);
int n;
if ( str >> n )
{
// Extraction is successful.
// Add another check.
// Get the next character.
// It has to be a whitespace character or EOF for the input
// to be an integer.
// If it is neither, don't accept the input as an integer.
std::istream::int_type c = str.get();
if ( std::isspace(c) || str.eof() )
{
// Use n.
}
}
You just check each character in your input string is a number, I have a simple example for your problem:
#include <stdio.h>
#include <string.h>
bool is_number(const char * s)
{
int length = strlen(s);
for (int i = 0; i < length; i++)
{
if (s[i] < '0' || s[i] > '9')
return false;
}
return true;
}
int main()
{
printf("Enter a string: ");
char myString[10];
gets(myString);
if (is_number(myString))
printf("%s is a number", myString);
else
printf("%s is not a number", myString);
}
I don't think you even need to check. According to the C++ API:
If the first sequence of non-whitespace characters in str is not a
valid integral number, or if no such sequence exists because either
str is empty or it contains only whitespace characters, no conversion
is performed and zero is returned.
SEE:
http://www.cplusplus.com/reference/cstdlib/atoi/
-
So, you should just be able to do:
// Convert the string
int value = atoi( myString.c_str() );
if ( value == 0 )
{
// The string was not a valid integer
}
else
{
// The string was a valid integer
}
'isnum()' function below checks if given string is comprised of numbers only. However it might not work if number is very large.
#include <bits/stdc++.h>
using namespace std;
bool isnum(string str){
for(int i=0;i<str.length();i++){
if((str[i]<'0') || (str[i]>'9'))return false;
}
return true;
}
int main() {
// your code goes here
int n=0,r=1;
string num;
cin>>num;
if(isnum(num)){
for(int i=num.length()-1;i>=0;i--){
n+=(r)*(int)(num[i]-'0');
r*=10;
}
cout<<n;
}
return 0;
}
You can check if there is any non-digit character in the string:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main()
{
std::string test;
std::cin >> test;
if(std::find_if(test.begin(), test.end(), [](auto x){return !isdigit(x);}) == test.end())
std::cout << "its a number" << std::endl;
else
std::cout << "not a number" << std::endl;
}

wrong output in strings

My program calculates the length of each word before space and compares it with a fixed number.
The number is chosen from another string (pi).
I don't know why but my variable FLAG is always set to false so I always get the same output.
I don't know where the problem is. Please help out
#include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <algorithm>
#include <iomanip>
using namespace std;
int main() {
int t=0,num;
int i,j,len,space;
bool FLAG;
string pi ="31415926535897932384626433833",song;
cin>>t;
while(t--){
len=0,space=0,i=0,j=0,num=0,FLAG=true;
cin.ignore();
getline(cin,song);
// problem from here
while(1) {
i=0,num=0,FLAG=true;
len=song.length();
space=song.find(' ');
if(space==-1){
if(len==pi[j]){
FLAG=true;
break;
}
else{
FLAG=false;
break;
}
}
else{
while(i<space){
num++;
i++;
}
if(num==pi[j]){
FLAG=true;
j++;
num=0;
i=0;
song.erase(0,space+1);
cout<<song<<endl;
}
else{
FLAG=false;
break;
}
}
}
// to here
if(FLAG==true){
cout<<"It's a pi song."<<"\n";
}
else{
cout<<"It's not a pi song."<<"\n";
}
}
return 0;
}
You are comparing an integer with a character value. i.e. you are comparing 3 with '3'. To get a number from a character digit, subtract '0'.
So you could write
if (len==(pi[j] - '0'))
Also, please learn to use a debugger, you can step through your code to find the line that doesn't work.

Supposed to print number of upper and lowercase but returns 1 and exits program

I had the program working until I wrote it with a void function. I have no idea where I've messed up. It returns 1 and gives no other errors.
#include <iostream>
#include <string>
using namespace std;
char response;
string s;
int upper, lower, other, count;
void capCheck(string);
int main()
{
count = 0;
upper = 0;
lower = 0;
do
{
cout<<"Get the number of upper and lower case letters in your sentence!!"<<endl;
cout<<endl;
cout<<"Type your sentence below without spaces.."<<endl;
cin>>s;
capCheck(s);
cout<<"Would you like to continue? Y/N"<<endl;
cin>>response;
}while(response == 'y' || response == 'Y');
return 0;
}
void capCheck()
{
while(s[count] != 0)
{
if(s[count] >= 'a' && s[count] <= 'z')
{
lower++;
count++;
}
else if (s[count] >= 'A' && s[count] <= 'Z')
{
upper++;
count++;
}
else
other++;
}
cout<<"The number of uppercase letters are: "<<upper<<endl;
cout<<"The number of lowercase letters are: "<<lower<<endl;
}
Just change void capCheck() for void capCheck(string s) in your function declaration. It works fine for me.
Some comments on the code: try not to use global variables and improve indenation.
At your function definition put
void capCheck(string s) {
// ...
}
See live demo.
The provided function definition signature
void capCheck() {
// ...
}
doesn't match the actual declaration of your function prototype's signature
void capCheck(string);
"I have no idea where I've messed up. It returns 1 and gives no other errors."
The program doesn't compile in the form you've posted your code. Probably the build process stops prematurely (note there isn't any path in your main() function returning 1).