How to get keyboard inputed ints one by one

I am trying to create a program to read arbitrary long integer numbers and then print them. My idea is to 1. create a dynamic array of integers or chars
1
2
3
    int arraysize = 5; 
    char* a = new char[arraysize]; 
    int n = 0;


or
1
2
3
int arraysize = 5; 
    int* a = new int[arraysize]; 
    int n = 0;


2. Read the digits from the keyboard one by one and fill the array
3. Once the array is filled, double the size of the array, and keep putting the numbers in the array.
4. Print the number using cout << a;

Now I have questions.

1.How do you use cin to read character by character?
2.How do you determine the end of the sting of integers?

I really appreciate your time for answering my questions. Examples are a plus.

that behaviour corresponds with the std::string class.

2.How do you determine the end of the sting of integers?

Either you storage the size of the string, or you reserve an special character as the end.
If you want to use cout with char * you need to terminate the array with a '\0'
Is there another way to I could pass all the digits of the string of integers to an array without using the string datatype? My professor doesn't want me to use string data type.
check iostream::get

My professor doesn't want me to use string data type.
Did he/it/she want that you make your own string class?
Last edited on
Did he/it/she want that you make your own string class?


He said strings was going to be too slow. I don't know what he meant by that since I didn't have a chance to ask him. He only tool me to use a dynamic array. That was it! However, I assume that he said so because we have to convert the number later to binary representation. And to be honest I don't have an idea on how to do this for an arbitrary number integer.

BTW, thanks you for the answers. I appreciate it!
Why don't you come out with your program and we take a look. Below is how I would implement 3. Once the array is filled, double the size of the array, and keep putting the numbers in the array.

Enter a number press Enter, enter a number press Enter, press <Ctrl-D> to signal end of input stream.

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>
using namespace std;

int main() {

int arraysize = 5; 
char* a = new char[arraysize];
int n = 0;

//a while loop to read from keyboard and not found terminating character
char X;
while (cin >> X) {
if (n < sizeof(a)/sizeof(*a)) {
  *(a+n)=X; //this X is what you get from keyboard
  n++;
} else {
  char* tmp = new char[n*2]; //increase array to 2 times
  for(int i=0; i<n; i++) *(tmp+i) = *(a+i);
  for(int i=n; i<(n*2); i++) *(tmp+i) = '\0';
  delete [] a;
  a = tmp;
  *(a+n)=X; //this X is what you get from keyboard
  n++;
} 
}//end while

cout << a << "\n";
return 0;
}  
Last edited on
Topic archived. No new replies allowed.