I am doing an assignment where the first part requires us to prompt the user to enter a string. We need to store this input as a cstring on the heap (not a std::string so we get a better understanding of cstring). I have got something that works fine:

char *input = new char[500];
cout << "enter a string: ";
cin.getline(input, 500);

But I feel like this isn't a very good way to do it in regards to creating an array of 500 and hoping they don't exceed this character limit. Is there a way I can do this without making a ridiculously large array and likely not using anywhere near that much? This seems a very amateurish way of going about it. I think it is possible using std::string but I have to use cstring :(

有帮助吗?

解决方案

The C way would be to allocate the buffer with malloc, read the appropriate number of bytes, and figure out if you got the whole string. If you didn't read enough, then you can use realloc to expand the buffer, and read more where you left off.

其他提示

we can do like this:BUILD A DYNAMIC STRING BUFFER YOURSELF.

  1. Alloc a heap memory(80 is enough).
  2. You control the input by yourself.You can read just one character from the input stream every time.If the size of the memory is not enough to contain this character,just alloc another enough one.
  3. When you get the character '\n'(or others) just stop reading.

Yes,this is what the c++ library does!The buffer is actually a queue.

c++ improved performance... so this takes an array and points to that array with pointer

#include <cstring>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;

int main()
{
char name[100];
//string userInput[26];
int i=0, n=0;
cout<<"your name? ";
cin>>name;
cout<<"Hello "<<name<< endl;

char *ptr=name;
for (i = 0; i < 20; i++)
{
cout<<i<<" "<<ptr[i]<<" "<<(int)ptr[i]<<endl;
}   
int length = 0;
while(name[length] != '\0')
{
    length++;
    }

            for(n=0; n<3; n++)
                    {

                if (strncmp(ptr, "r2d2", 4) == 0)
                    {
                    cout << "you found r2d2bob" << ptr[i];
                    }

        }
cout<<name <<"is"<<length<<"chars long";
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top