dynamic array running error

here is my cpp file, it doenst have compiler error, but when i run it and input value in the array, and cout some trash output. I am not very good understanding about dynamic Array, am i using the pointer correctly, or do i have some logic error in the code? and my header file just contain some functions that store data and return true or false to store the data in array

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include "DynamicArray.h"

using namespace std;

int main()
{
    DynamicArray<int> a;
    //initial the char bufs array have size = 100
    char *buf1=new char[100];
    char *buf2=new char[100];
    int index = 0;
	int num = 0;
	//keep letting user input data 
	//if it return true
    while(true)
    {
	  cout << "Input an index and a value [Q to quit]: ";
	  cin >> buf1[num];
	  //loop untill enter q or Q
	  //then break, and return false
	  if(buf1[num] =='q' || buf1[num] == 'Q')
	     break;
	  cin >> buf2[num];
	  cin.ignore(1000,10);
	  //cout<<"buf1:   "<<buf1<<"buf2:    "<<buf2<<endl;
	  //atoi is about to read them into a string buffer and convert
	  index = atoi(buf1);
	  a[index] = atoi(buf2);
	  num++;
    } 
	
	//we had stored the value and index in to the array
	//then we pass the data to containskey() function
	//to test true or false
	//so we show all the data that user input if they have
	//vaild input, otherwise invaild input will be return 
	//false and no show
    cout << "I stored this many values: " << a.Size() << endl;
    cout << "The values are: " << endl;
    for( int i = 0; i < a.Capacity(); i++)
    {
      if(a.ContainsKey(i))
        cout << i << " " << a[i] << endl;
    }
	
	return 0;
	
    
};
 
cin >> buf1[num];

This reads one character from cin and stores it in the buf1 array at position num. Is that what you want?
Yes, i understand this, i am trying to store in buf1, and out put the value, but it comes out some nonsense number
I think Peter87 is right. You are reading a SINGLE character at lines 21 and 26. So if the user enters "23" for the index and "144" for the value, line 21 will read '2' and line 26 will read '3'. Then when you call atoi() who knows what value you'll get because buf1 and buf2 are not null terminated.

I think num should be the number to store. Try replacing the while loop with this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    while (true) {
	cout << "Input an index and a value [Q to quit]: ";
	cin >> buf1;
	//loop untill enter q or Q
	//then break, and return false
	if (buf1[0] == 'q' || buf1[0] == 'Q')
	    break;
	cin >> num;
	cin.ignore(1000, 10);
	//cout<<"buf1:   "<<buf1<<"buf2:    "<<buf2<<endl;
	//atoi is about to read them into a string buffer and convert
	index = atoi(buf1);
	a[index] = num;
    }

Topic archived. No new replies allowed.