cin.get not holding console

Following is a simple programme which i wrote for calculating array length.

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

int arz(int ard[])
{ int d=0,i=0;
while(ard[i]!=0)
{ d++;
i++;
}
return d;

}

int main()
{    int x, i ,j;

    cin>>x;
    int are[x+1];
    for(i=0;i<x;i++)
        cin>>are[i];
    are[x]=0;
    cout<<"length is"<<arz(are);
    cin.get();
    return 0;
}

The problem here occuring is that cin.get is not able to hold the console.I tried replacing header file by #include<bits/c++.h> but it was of no use. Can anyone please help me , why it is so ?
What is the correct way to hold console.
Hi,

I'm guessing that by "not able to hold the console" you mean that the console closes immediately after having executed your program. If so, then this link will be helpful:

http://www.cplusplus.com/forum/beginner/1988/

Not that you asked for a different way, but here is an alternative way to do your program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
#include<limits>

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

int main() {
    int x, i;
    
    cout << "Enter number of elements: ";
    cin >> x;
    
    int are[x+1];

    for(i=0;i<x;i++){
        cout << "Enter a number: ";
        cin>>are[i];
    }
    
    cout << "Length is: " << (*(&are+1) - are)-1 << "\n\n";  // See Ref.#1 below the code

    // then something like the code below to keep console open (read the thread provided 
    // for several different methods to accomplish this)

    cout << "Press ENTER to continue...";
    cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

return 0;
}


Ref.#1. https://www.geeksforgeeks.org/how-to-find-size-of-array-in-cc-without-using-sizeof-operator/

Hope that helps.
Last edited on
17
18
 cin>>x;
    int are[x+1];


@brijvit

I would advise not to do this, variable length arrays are not allowed in the C++ standard. Use a std::vector instead, no need to worry about the length, it has a size function. std::vector was invented to get around the problems associated with arrays.

Overall, try to get into a C++ mindset, rather than thinking in C. By this I mean use the STL containers, classes and algorithms.

Good Luck !!
Topic archived. No new replies allowed.