简体   繁体   English

C ++动态数组问题

[英]c++ dynamic array problems

dynamic arrays are known for letting you store a string or any data type without having to declare it size the problem that i'm facing with my c++ is the following : 动态数组以让您存储字符串或任何数据类型而不必声明其大小而闻名,而我用c ++所面临的问题如下:

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char*sentence=new char;
cout<<"enter a sentence (end with *) : ";
cin.getline(sentence,'*');
cout<<"sentence : "<<sentence<<endl;
system("pause");
return 0;
}

the cin.getline won't stop on the character '*' so the limit will be set when i press enter. cin.getline不会停留在字符“ *”上,因此当我按Enter键时将设置限制。 but if i want to use only the return key it will read the first 9 characters of the string: 但是,如果我只想使用返回键,它将读取字符串的前9个字符:

 int main()
    {
        char*sentence=new char;
        cout<<"enter a sentence : ";
        cin.getline(sentence,'\n');
            cout<<"sentence : "<<sentence<<endl;
        system("pause");
        return 0;

    }

but it will work only if i limit the number of characters : 但只有在我限制字符数的情况下,它才有效:

int main()
{
char*sentence=new char;
cout<<"enter a sentence : ";
cin.getline(sentence,100,'*');
system("pause");
return 0;
}

but i want to let the user input a sentence without limits how to do it without setting the number of characters in the cin.getline nor when declaring the dynamic array . 但是我想让用户输入一个无限制的句子,如何在不设置cin.getline中的字符数或声明动态数组时进行设置。

std::string line;
std::getline(std::cin, line);

You never have to worry about the storage in a std::string , it works it all out for you. 您不必担心std::string的存储问题,它可以为您解决所有问题。 By the way, new char; 顺便说一句, new char; doesn't create a dynamic array of char s, it creates a pointer to just one char . 不会创建char的动态数组,而是创建仅指向一个char的指针。 Also, see getline . 另外,请参见getline

char* sentence=new char ; allocates a single char 分配一个char

Use: 采用:

char* sentence=new char[100];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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