I am new in C++ and now I am learning how cin and cout works. The case is, as you can see in the code below I create a string, and a char * in order to compare the C way to read a string and the C++ way. In C++, it makes sense that if I create a string then I worry about to set this string to NULL?
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#define SIZE 10
using namespace std;
int main () {
cout << "Write Something: \n";
string f1;
char *p;
p = (char *) malloc(SIZE); // This is how I will use it in c
getline(cin, f1);
cout << "Write Something else: \n";
scanf("%s", p);
cout << f1 << "1\t";
printf("%s2\n", p);
free(p);
p = NULL; // After the pointer has been freed, we set it to NULL
cout << "p freed\t";
f1.clear();
cout << "f1 deleted\t";
return 0;
}
std::stringcan be empty (i.e.,""), or it can have one-or-morechar. It cannot beNULL.free()mallocornewornew[]in about a decade. Instead I usestd::vector, orstd::unique_ptr, or if I really have tostd::shared_ptr.stringsaren't likeStringin java, always will have a value different to NULL?std::stringis not like JavaString. (Likewise with JavaScript, except the OO is even more different.)