-1

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 :

#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. but if i want to use only the return key it will read the first 9 characters of the string:

 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 .

2 Answers2

3
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. By the way, new char; doesn't create a dynamic array of chars, it creates a pointer to just one char. Also, see getline.

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
1

char* sentence=new char ; allocates a single char

Use:

char* sentence=new char[100];

P0W
  • 46,614
  • 9
  • 72
  • 119