Search code examples
c++stringfunctionintboolean

Why do these perfectly similiar codes not work?


I'm learning about functions in C++ and I saw this code on Tutorialspoint which tells us whether the input is an int or a string.

Link to the Tutorialspoint article : https://www.tutorialspoint.com/cplusplus-program-to-check-if-input-is-an-integer-or-a-string

This is the original code:

#include <iostream>
using namespace std;
//check if number or string
bool check_number(string str) {
   for (int i = 0; i < str.length(); i++)
   if (isdigit(str[i]) == false)
      return false;
      return true;
}
int main() {
   string str = "sunidhi";
   if (check_number(str))
      cout<<str<< " is an integer"<<endl;
   else
      cout<<str<< " is a string"<<endl;
      string str1 = "1234";
   if (check_number(str1))
      //output 1
      cout<<str1<< " is an integer";
   else
      //output 2
      cout<<str1<< " is a string";
}

The original one works perfectly fine, but my code either only shows ouput 1 or only shows output 2 no matter whether you enter an int or a string.

My code:

Note : my code was written on an online compiler. Link to the compiler : https://www.onlinegdb.com

#include <iostream>
using namespace std;
//the function which checks input
bool check(string s){
    for(int i = 0; i < s.length(); i++)
    if(isdigit(s[i]) != true)
    return false;

return true;     
    
}
//driver code
int main(){
    string str = "9760";
    if(check(str)){
        //output 1
        cout<<"Thanks! the word was " <<str;
    }
    else{
        //output 2
        cout<<"Oops! maybe you entered a number!";
    }
}    

Ouput when executing my program : Thanks! the word was 9760

Link to the code project: https://onlinegdb.com/HkcWVpFRU

Thank you!


Solution

  • You are checking if the char is a digit and returning false if it is, you should change it to

    bool check(string s){
        for(int i = 0; i < s.length(); i++)
            if(isdigit(s[i])
               return false;
    return true;     
    }
    

    a sidenote, if you want to check for false you can do (!bool) instead of (bool != true) it looks cleaner