简体   繁体   中英

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++;
}
  • 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];
    }
    delete[] name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM