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