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
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include "DynamicArray.h"
usingnamespace std;
int main()
{
DynamicArray<int> a;
//initial the char bufs array have size = 100
char *buf1=newchar[100];
char *buf2=newchar[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;
};
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;
}