c++for-loop

Code breaks after answer with a dot and skips the rest of the code


If i don't use dots like 1.5 it will break but if it's whole number like 15 it works perfectly

I tried to looking for it in the internet but didn't find the fix it

#include <iostream>
using namespace std;
int main()
{
    int n,sk,i,a,p,b,c;
    int kiek=0;
    cout << "insert how many shops did he went to" << endl;
    cin >> n;
    b=n;
    cout << "how many thing did he buy in every shop" << endl;
    cin >> p;
    c=p;

   for(int n=0; b>n; n++)
    {
    a=0;
    for (int i=1; i<=c; i++)
    {
        cout << "insert "<< i << " product price"<< endl;
        cin >> sk;
        a=a+sk;
        }
          cout<< "spent " << a<< " pmoney"<< endl;
}
    return 0;
}

it should let me type how much did he spent with every product but if i add a . it skips everything and shows only one


Solution

  • Problem

    An integer type cannot store decimal values.

    When you execute int sk; cin >> sk; and you enter "1.5", the operator >> will store 1 in sk and leave .5 in the stream. The next time you execute cin >> sk, the stream will try to read the next integer with what is left in the stream, but will fail because "." cannot be converted to an integer, leaving your stream in a 'fail' state. For this point, all cin instructions will fail to read the next integer.

    Solution

    To fix the problem, I suggest to declare price values as doubles: double a,sk. However, the same problem will occur if you enter an invalid floating point value. I strongly suggest to correctly manage stream errors and react accordingly. You can access the state using rdstate() or its related methods (good, fail, bad, eof).