I've just noted something... There are a handful of problems regarding the use of strings. In most of them I plan a solution in C, which uses null-terminated char arrays as strings.
As I'm aware the use of scanf and gets is not recommended, I always use fgets with strchr together, in order to address the ENTER-in-the-string problem.
What I basically do, is the following:
Code: Select all
/* I'll read 50 characters, plus the ENTER, plus the '\0' */
char string[52] = {0};
fgets(string, 52, stdin);
/* "Empty" the input buffer */
setbuf(stdin, NULL);
/* Once I get the string, I get rid of the ENTER */
char *enter = strchr(string, '\n');
if (enter != NULL) *enter = '\0';
Then, I rewrite the program in C++. As I know there's the string library, I use it with iostream, so I write this equivalent. Note that I don't modify the essential algorithm, just the I/O, because I know I can use array notation in C++ strings:
Code: Select all
/* The same as above */
string str;
cin >> str;
Am I doing something wrong when I deal with C strings?
Any help is appreciated