-5

Firstly, I want to say that I'm a beginner. Sorry for my stupid questions.

My program should ask for the amount of words you want to put in. It's specifically said that this tab length is the length of pointers tab pointing to the words tab (may sound confusing, but English isn't my first language, my apologies, I also dont really understand pointers yet).

The words tab should also have exact length for each word, hence the strlen. What am I doing wrong?

int il,len;
string x;
cout<<"Amount of words: ";
cin>>il;
int **t;
t=new int*[il];
for(int i=0; i<il; i++)
{
    cout<<"Word: ";
    cin>>x;
    len=strlen(x);
    t[i]=new string[len];
    cout<<endl;
}
cout<<"You wrote:"<<endl;
for(int i=0; i<il; i++)
{
    cout<<t[i];
    delete [] t[i];
}
delete[] t;
DeiDei
  • 10,205
  • 6
  • 55
  • 80
Akil6
  • 9
  • `strlen` doesn't take a class string object but a const pointer to character string `char*` – Raindrop7 Jan 22 '17 at 22:30
  • What is tab? Do you mean the array (as in table)? – Paul Rooney Jan 22 '17 at 22:30
  • 3
    `t` is of type `int**`, and `t[i]` is of type `int*`. You cannot assign a `std::string*` object to `int*`. Coupled with some other errors in your code; You may want to glance over some [resources](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to help you understand C++ type system broader than we can explain here – WhiZTiM Jan 22 '17 at 22:31
  • Have you compiled this with some (all?) warnings enabled – Ed Heal Jan 22 '17 at 22:35

1 Answers1

1

strlen() doesn't take a class string object but instead it takes a pointer to character string char*:

len = strlen(x); // error so correct it to:
len = x.length();

also you cannot initialize a pointer to an integers to class string:

int **t;
t[i]=new string[len];
  • you really want an array of strings but the code is really a mess so if you want this how:

    int il;
    
    cout << "Amount of words: ";
    cin >> il;
    
    string *t;
    t = new string[il];
    
    for(int i = 0; i < il; i++)
    {
        cout << "Word: ";
        cin >> t[i]; // there's no need for a temporary string `x`; you can directly input the elements inside the loop
        cout << endl;
    }
    
    cout << "You wrote: " << endl;
    
    for( int i = 0; i < il; i++)
        cout << t[i] << endl;
    
    delete[] t;
    
Raindrop7
  • 3,889
  • 3
  • 16
  • 27