How to tell difference between an int and string

Hello, I'm new to this and the answer is probably obvious but is there something I can put as that if condition so that if they type a number its prints "invalid name"?

Also, is there a way to tell how many letters they typed?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;

main()
{
string a;
cin >> a;

if (   )
{
    cout << "invalid name";
}
else
{
    cout << endl << "your name is " << a;
}
return 0;
}
Two ways: look for all-digits in the name; try to convert to a number.

Here is how to do the second method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <sstream>
#include <string>

int main()
{
  std::string name;
  {
    std::cout << "Name? ";
    getline( std::cin, name );
    std::istringstream ss{ name };
    double x;
    ss >> x >> std::ws;
    if (ss.eof())
    {
      std::cout << "A name cannot be a pure number.\n";
      return 1;
    }
  }
  std::cout << "Good job " << name << "!\n";
}

Hope this helps.
You can loop through the string with a loop, and check if any of the individual characters have an ascii value between 48 and 57 (those are the ascii values for number characters - https://www.learncpp.com/cpp-tutorial/chars/ )

1
2
3
4
5
6
int numbersinString = 0;
for(int i = 0; i < a.size(); i++)
{
     if(a[i] >= 48 && a[i] <= 57)
          numbersinString++;
}


If you forbid numbers at all, then if a number is found you can leave the loop to verbally attack the user. If you only want the name to not be ONLY numbers or not be mostly numbers, you can check the amount of numbers in the name with the length of the string.


EDIT: Don't forget the "int" in front of "main"
Last edited on
1
2
3
if(a[i] >= 48 && a[i] <= 57)
if(a[i] >= '0' and a[i] <= '9')
if( isdigit(a[i]) )



> Also, is there a way to tell how many letters they typed?
define letter
Topic archived. No new replies allowed.