Arey M Salih Arey M Salih - 22 days ago 5
C++ Question

How to use pointers with strings?

I know my question is not specific but let me explain it this code

char name[5][30];
for (int i = 0; i < 5; i++)
cin >> name[i];

for (int i = 0; i < 5; i++)
cout<<name[i];


in the example above i created an array of characters where you can input five words each with 30 bit length. and it works just fine but when i try to use a pointer like so when you don't know how many words you are about to input. I get an error in line 5 saying a value of type int cant be asigned to char and i understand the error but how how to get pass this problem?

int n;
cout << "Number of names" << endl;
cin >> n;
int *name;
name = new char[n][30];
for (int i = 0; i < 5; i++){
cin >> *name;
name++;

}

for (int i = 0; i < 5; i++){
cout << *name;
name++;
}

Answer
  • Use char, not int.
  • Incrementing name doesn't seem good idea because it have to be returned to the first element before printing. I used array indexing operator.
  • I guess n input & output should be done instead of fixed 5 input & output.
int n;
cout << "Number of names" << endl;
cin >> n;
char (*name)[30];
name = new char[n][30];
for (int i = 0; i < n; i++){
    cin >> name[i];

}

for (int i = 0; i < n; i++){
    cout << name[i];
}