Akshit Bansal
Akshit Bansal

Reputation: 127

Detecting if input is a string or an integer

Please tell me what is wrong in my approach.

#include <iostream>
#include <string>
using namespace std;

string datatype(string x) {
    for (int k = 0; k < strlen(x.c_str());) {
        for (int i = 0; i < 10; i++) {
            char z = i;
            if (x[k] == z) {
                k++;
            }
            else {
                return "string";
            }
        }
    }
    return "int";
}

int main() {
    string inp;
    cin >> inp;

    cout << datatype(inp);
}

Whatever i enter, it always returns "string". I have seen the other questions posted here but please tell me what is wrong in my approach.

Upvotes: 0

Views: 111

Answers (2)

Silvano Cerza
Silvano Cerza

Reputation: 970

The standard library has the isdigit function that tells you if the char is a digit.

Here you check that each char of your input is a digit, as soon as a character that is not a digit is found string is returned, else int.

For example 1234 returns int, sdf returns string.

string datatype(string str) {
    for (unsigned char c : str) {
        if (!isdigit(c)) {
            return "string";
        }
    }
    return "int";
}

Edit: This solution also handles leading - and +. It will return int for -10 and +10 but returns string for +1+1 or -10+10.

string datatype(string str) {
    if (str.size() == 1) {
        return isdigit(str[0]) ? "int" : "string";
    }

    bool isInt = true;
    for (int i = 1; i < str.size(); i++) {
        isInt = isInt && isdigit(static_cast<unsigned char>(str[i]));
        if (!isInt) {
            break;
        }
    }

    if (isInt) {
        unsigned char c = str[0];
        isInt = isInt && (c == '-' || c == '+' || isdigit(c));
    }

    return isInt ? "int" : "string";
}

Upvotes: 4

Itisha
Itisha

Reputation: 30

First of all Include (cstring) as header since x.c_str is not in iostream and string. Then, When you are doing char z=i; here you are not storing the character equivalent of i in z but the ascii value of i. Next, You are returning string at the first mismatch between i and x[k]. You should return string if you cannot find a match with any of the possible 10 digits.

You can have a look at the modified code.

#include <iostream>
#include<cstring>
#include <string>
using namespace std;

string datatype(string x) {


    for (int k = 0; k < strlen(x.c_str());k++) {
         int flag=0;
        for (int i = 0; i < 10; i++) {
           // char z = i;
            if ((x[k]-'0') == i || (k==0 && x[k]=='-')) {
                flag=1;
               break;
            }

        }
          if(flag==0)
          return "string";


    }
    return "int";
}

int main() {
    string inp;
    cin >> inp;
   cout << datatype(inp);
}

Upvotes: 0

Related Questions