[Solved] how to assign number to following characters “@” or “#” or “^” and “*”


You could use a simple character array:

static const char symbols[] = {'@', '#', '^', '*'};
char c;
std::cin >> c;
unsigned int value;
for (value = 0; value < sizeof(symbols); ++value)
{
  if (c == symbols[value])
  {
    break;
  }
}
if (value >= sizeof(symbols))
{
  // Symbol not found.
}
else
{
  value += 2;
}

The above code searches the array of characters for the symbol. If the symbol exist, the index is the value associated with the symbol. However, since the @ symbol is first and the array indices start at 0, an adjustment is made by adding 2 to the array index after the value is found.

Edit 1: Lookup table
Another method is to use a lookup table. Create a structure containing the relationship, then make an array of those structures.

struct Relationship
{
  char  c;
  unsigned int value;
};

Relationship table[] = 
{
  {'@', 2}, {'#', 3}, {'^', 4}, {'*', 5},
};
const unsigned int TABLE_SIZE =
    sizeof(table) / sizeof(table[0]);

char c;
cin >> c;
unsigned int value = 0;
for (unsigned int i = 0; i < TABLE_SIZE; ++i)
{
    if (table[i].c == c)
    {
      value = table[i].value;
      break;
    }
}

Edit 2: Using switch
Another method is to use the switch statement:

char c="\0";
cin >> c;
unsigned int value;
switch (c)
{
    case '@': value = 2; break;
    case '#': value = 3; break;
    case '^': value = 4; break;
    case '*': value = 5; break;
    default: value = 0; break;
}

The if/else ladder:
Edit 3: The program:

#include <iostream>

using std::cin;
using std::cout;


int main(void)
{
    cout << "Enter symbol: ";
    char c;
    cin >> c;
    unsigned int value = 0U;
    if (c == '@')
    {
      value = 2;
    }
    else if (c == '#')
    {
      value = 3;
    }
    else if (c == '^')
    {
      value = 4;
    }
    else if (c == '*')
    {
      value = 5;
    }
    else
    {
      value = 0;
    }

    cout << "\nYour value: " << value;
    return 0;
}

Sample run:

C:\Debug>symbol_matching.exe
Enter symbol: @

Your value: 2
C:\Debug>symbol_matching.exe
Enter symbol: *

Your value: 5
C:\Debug>symbol_matching.exe
Enter symbol: ^

Your value: 4
C:\Debug>symbol_matching.exe
Enter symbol: #

Your value: 3

Note: I typed the special symbol, then pressed Enter.

2

solved how to assign number to following characters “@” or “#” or “^” and “*”