简体   繁体   中英

C++ ->Trying to read a line of text word by word. How to make a pointer equivalent of the current 2 dimensional array used to store the input

Wrote this program to read a user input, word by word

#include<iostream>
#include<cstring>

int main()
{
    using namespace std;
int i=0;
    char input[50][50];

    cout<<"Enter input: ";
    cin>>input[i];

    while(strcmp("q",input[i]))
    {
        i++;
        cin>>input[i];
    }
    cout<<endl;

    for(int j=0;j<i;j++)
        cout<<input[j]<<" ";
    return 0;
}

Currently using a two-dimensional character array to store the input. I'm not that good with pointers since i just read about those.

Is there a pointer equivalent of char input[50][50] ? I know this range of [50] is a bad idea. Using pointers should solve it right?

I tried doing this-> char* input= new char[50] , but i guess this is the wrong way? Does char* input= new char[50] create a pointer to array of strings or a pointer to array of characters?

Please keep it simple. just started with arrays.

char* input= new input[50]; is wrong;

char * input = new char[50]; is correct.

its creates a dynamic 1D array of characters. It is not the array of pointers. If you want to create an 2D array of characters

here is the syntax

char * arr = new char*[rows]; //creates an 1D array of character pointers
for(int i=0;i<rows;i++)
arr[i]=new char[columns]; //Creates Array for every Row, to make it 2D array

You can assume 2D character array as a 1D string array, because string is also a character array. More I would suggest you to use strings you can easily manipulate a string.

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