cin running only once inside while loop

Tsutsui Tsutsun

I have seen another post with nearly the same title but it didn't help at all since they had a mistake in there code. I just want to get as many values as the client puts in and add them but it only takes the first input

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

int issa_def() {
    int issa[] = {};
    int half_ans_issa[] = {};
    int i  = 0;
    int cn = 0;
    while(true) {
        cout << "enter prices of items ordered by issa: ";
        cin >> cn;
        if(cn == 111) {
            break;
        }
        else {
        issa[i] = cn;
        }
        i++;
        cin.clear();
    }
    int a = 0;
    for(int i = 0;i <= sizeof(issa);i+=2) {
        int ans = issa[i] + issa[i+1];
        half_ans_issa[a] = ans;
        a++;
        cout << issa[i] << "\n" << issa[i+1] << "\n";
    }
    a = 0;
    cout << half_ans_issa[a];
}
int main() {
    issa_def();

}

here is the output after printing the values of the first and second input i put in and the sum

C:\Users\akram\Documents\code>a.exe
enter prices of items ordered by issa: 5
enter prices of items ordered by issa: 5
enter prices of items ordered by issa: 111
first input:5
second input:0
output:5

note: 111 is the exit code

i turned on compiler warnings as stated by user –πάντα ῥεῖ and i got the error

dahra.cpp:23:18: warning: comparison between signed and unsigned integer express
ions [-Wsign-compare]
  for(int i = 0;i <= sizeof(issa);i+=2)
xuman

What is the size of your arrays? You initialize them with {} so they are just an int* without any memory allocation. As soon as you insert values to issa[i] you will overflow.

For a similar reason you cannot iterate from 0 to sizeof(issa) (including the latter). First, sizeof gives you the size in bytes, not the number of array elements. Second, should sizeof works as you expect, you iterate through (n+1) elements, not (n). Finally, if the array has an odd number of elements, you access memory outside the array (issa[i+1]). You should use std::vector to get an arbitrary number of inputs.

Finally, you should have a return of your issa_def function.

Wrapping up, when you insert elements in your array you should use

issa.push_back(cn)

And, when iterating through issa, you should consider even/odd arrays, as well as the appropriate size of the array:

for(int i = 0; i < issa.size() - 1; i += 2) {
  ...
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related