c++arraysinputwhile-loopmultiple-input

How do i take user input of an Arithmetic Expression like 5-8+7*4-8+9 or 1+5?


I am solving a problem for finding maximum value of an arithmetic expression. But I am having problem in taking input for the expression as no of characters are not fixed.

Input Format:

But I want digits and symbols in different arrays(digits in an int array and operations in a char array) for my solution.

This is how I implemented originally:

  string s;
  std::cin >> s;

  n=s.size();
  cout<<"n= "<<n<<endl;

  vector<long long> no;
  vector<char> ops;

  for(int i = 0; i <n; i++)
  {
    if(i%2==0)
    {
      no.push_back(s[i]);
    }
    else{
      ops.push_back(s[i]);
    }
  }

But I am not being able to get required input, instead getting this:

INPUT:
5-8+7*4-8+9

OUTPUT:
n = 11
no[0] = 53
no[1] = 56
no[2] = 55
no[3] = 52
no[4] = 56
no[5] = 57
ops[0] = -
ops[1] = +
ops[2] = *
ops[3] = -
ops[4] = +

I have also tried one more solution:

  vector<long long> no;
  vector<char> ops;

  int i=0;
  while(cin)
  {

    cout<<"i= "<<i<<endl;
    if(i%2==0)
    {
      int s;
      cin>>s;
      if(s=='\0')
      {
        exit();
      }
      cout<<"s= "<<s<<endl;
      no.push_back((int)s);
      cout<<"no= "<<no[i/2]<<endl;
    }
    else
    {
      char s;
      cin>>s;
      if(s=='\0')
      {
        exit();
      }
      cout<<"s= "<<s<<endl;
      ops.push_back(s);
      cout<<"ops= "<<ops[(i-1)/2]<<endl;
    }
    i++;
  }

But this goes into infinite loop.

Please help me out


Solution

  • Your output seems to be correct, but as already mentioned in the comments, your values are read as characters, not as digits, so a conversion needs to be done.

    In order to do this, it might be helpful to understand that, in ASCII, the digits have following value:

    Character ASCII-code value
          '0'         48     0
          '1'         49     1
          '2'         50     2
          '3'         51     3
          '4'         52     4
          '5'         53     5
          '6'         54     6
          '7'         55     7
          '8'         56     8
          '9'         57     9
    

    How to get the value out of the character value? Easy :

    value(<character>) = ASCII_code(<character>) - ASCII_code('0'), or:
                       = ASCII_code(<character>) - 48