Array

I want use write a loop that the user can enter int. the user can enter infinite number of int until they enter -1. And I want to use array to store the input int except -1. how can I write the code? Below is the code that I have written without array. can someone help me?


int d;
while(d>=0){
cout<<"Add divisor: ";
cin>>d;

if(d==-1)
break;
}
Also I want to print the input int out after the process
You can't.

An array can only hold a fixed amount of numbers, so if the user can enter an infinite number of integers you can not be sure that you can store them in an array. If you really need an infinate number of inputs, google for "std::vector" or "linked list".

If you are working on the same assignment as Wong1546 (http://www.cplusplus.com/forum/beginner/199657/), kindly combine the topics.

Also try posting the code that you currently have (use the "<>" button to format it as source code) and describing the problem that you encounter in your own words. It will make the answers you get so much more useful.
Hello Luke,

The code will work,but I will suggest that you initialize "d" with:
1
2
3
int d = 0;
int d(0);
int d{ 0 };

either way will work, I prefer the third one.

If you want to print out what you enter just put the code after the break statement:
std::cout << "d = " << d << endl;.

If you want to use an array, define the array before the while loop. You will also need a counter variable to use the array. The code would be something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

int d[10]{ 0 };
int index{ 0 };

while(d>=0){
cout<<"Add divisor: ";
cin>>d;

if(d==-1)
break;

d[index++] = d;

std::cout << "The array contains:\n";

for (int lp = 0; lp < sizeof(d) / sizeof(int); lp++)
{
    std::cout << d[lp] << "\n";
}


Hope that helps,

Andy
hi Andy, I have tried your code few times but it keep saying there is error, do I need to use other library<==include<>?
Beside using array, how can I do the following process?


int d;
while(d>=0){
cout<<"d: ";
cin>>d;

if(d==-1)
break;
}


when compile

d:5
d:9
d:56
d:3
d:7
d:-1

5, 9, 56, 3, 7
closed account (LA48b7Xj)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v;

    for(int n; cin >> n && n != -1;)
        v.push_back(n);

    for(auto e : v)
        cout << e << ' ';
    cout << '\n';
}
Last edited on
Topic archived. No new replies allowed.