As I understand the question, in particular the “May be this can help us write our version of std::string
”, it's about
- doing what
std::getline
from the <string>
header does, to see what that involves.
That's already discussed in a good way by Bjarne Stroustrup in his paper “Learning Standard C++ as a New Language”, except that Bjarne discusses input via the >>
operator, which only inputs a single whitespace-delimited word.
Bjarne starts with pseudo-code for a hypothetical student's exercise:
write a prompt "Please enter your first name"
read the name
write out "Hello <name>"
He then presents one possible C++ solution:
#include<iostream> // get standard I/O facilities
#include<string> // get standard string facilities
int main()
{
using namespace std; // gain access to standard library
cout << "Please enter your first name:\n";
string name;
cin >> name;
cout << "Hello " << name << '\n';
}
And after some discussion he presents a C style solution, a DIY C style program to do just about the same as the C++ style solution:
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
void quit() // write error message and quit
{
fprintf(stderr," memory exhausted\n") ;
exit(1) ;
}
int main()
{
int max = 20;
char* name = (char*) malloc(max) ; // allocate buffer
if (name == 0) quit();
printf("Please enter your first name:\n");
while (true) { // skip leading whitespace
int c = getchar();
if (c == EOF) break; // end of file
if (!isspace(c)) {
ungetc(c,stdin);
break;
}
}
int i = 0;
while (true) {
int c = getchar() ;
if (c == '\n' || c == EOF) { // at end; add terminating zero
name[i] = 0;
break;
}
name[i] = c;
if (i== max-1) { // buffer full
max = max+max;
name = (char*)realloc(name, max) ; // get a new and larger buffer
if (name == 0) quit() ;
}
i++;
}
printf("Hello %s\n",name);
free(name) ; // release memory
return 0;
}
The two programs are not exactly equivalent: the C++ style first program only reads a single “word” of input, while the C program skips whitespace and then reads a complete line of input. But it illustrates what's involved for doing this yourself. In short, better use C++ style. ;-)