簡體   English   中英

C ++->嘗試逐字讀取一行文本。 如何使指針等效於用於存儲輸入的當前二維數組

[英]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

編寫該程序以逐字讀取用戶輸入

#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;
}

當前使用二維字符數組來存儲輸入。 我對指針不是很好,因為我只是閱讀了有關指針的內容。

是否有等效於char input[50][50]的指針? 我知道[50]的范圍不是一個好主意。 使用指針應該解決嗎?

我嘗試這樣做-> char* input= new char[50] ,但是我想這是錯誤的方式嗎? char* input= new char[50]創建指向字符串數組的指針或指向字符數組的指針?

請保持簡單。 剛開始使用數組。

char* input= new input[50]; 是錯的;

char * input = new char[50]; 是正確的。

它會創建一個動態的一維字符數組。 它不是指針數組。 如果要創建二維字符數組

這是語法

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

您可以將2D字符數組假定為1D字符串數組,因為string也是一個字符數組。 我更建議您使用字符串,您可以輕松地操作字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM