#include <iostream>
#include <cstring>
usingnamespace std;
int main()
{
char **table;
int *length; //pointer to an array in which the word lengths will be placed
int nof_words;
cout << "Enter the number of words: ";
cin >> nof_words;
table = newchar*[nof_words];
length = newint[nof_words];
for(int i = 0, temp; i < nof_words; i++){ //this loop is a system which
//enters words into a "table"
cout << "Enter the length of a " << i + 1 << ". word: ";
cin >> temp;
if(temp){
length[i] = temp;
table[i] = newchar[temp];
cout << "Enter the word: ";
char word[temp + 1];
cin >> word;
while(strlen(word) > (unsigned)temp){
cout << "Word is too long, try again: ";
cin >> word;
}
table[i] = word;
}
}
for(int i = 0; i < nof_words; i++)
cout << table[i] << endl;
delete [] table;
for(int i = 0; i < nof_words; i++)
delete [] table[i];
delete [] length;
return 0;
}
However, whatever words I enter I always get some wild output such as:
#include <iostream>
#include <cstring>
usingnamespace std;
int main()
{
char **table;
int *length; //pointer to an array in which the word lengths will be placed
int nof_words;
cout << "Enter the number of words: ";
cin >> nof_words;
table = newchar*[nof_words];
//length = new int[nof_words]; ///not required!
for(int i = 0, temp; i < nof_words; i++){ //this loop is a system which
//enters words into a "table"
cout << "Enter the length of word no. " << i + 1 << ": ";
cin >> temp;
if(temp>0){ /// >0
//length[i] = temp;
table[i] = newchar[temp+1]; // temp+1
cout << "Enter the word: ";
cin >> table[i]; ////// use a loop (or getline) for not overflowing
/*char word[temp + 1];
cin >> word; /// how long will it take ?? overflow may occur!
while(strlen(word) > (unsigned)temp){
cout << "Word is too long, try again: ";
cin >> word;
}
table[i] = word;*/
}
}
for(int i = 0; i < nof_words; i++)
cout << table[i] << endl;
//delete [] table; //not here
for(int i = 0; i < nof_words; i++)
delete [] table[i];
delete [] table; //here
//delete [] length;
return 0;
}