Most of the ways that doesn’t require string size checking would possibly cause buffer overflow error
Using scanf
Code
char line[100]; // this string can contain maximum 99 characters scanf("%[^\n]", line); // read every character until meet '\n' scanf("%*c"); // = cin.ignore(1), ignore '\n' character for the next input statement
Using std::getline (string)
Systax: istream& getline(istream & is, string & str, char delim = ‘\n’);
“Extracts characters from is and stores them into str until the delim character is found“.
“The delim character is extracted and discarded (it is not stored)” .
So we don’t have to ignore newline character after this function.
And since string is essentially a vector ( built in data type), we also don’t have to specify its size (length). Thus, although this function does not care about the size of string, it’s safe to use.
Code C++
string s; getline(cin, s);
Using std::istream::getline( char *)
Syntax: istream& getline(char * s, streamsize n, char delim = ‘\n’);
Extracts characters from istream object and stores them into s until the delim character is found or “n characters have been written to s (including the terminal null character)”.
The delim character is extracted and discarded.
So basically this function is the same as std::getline(string) function. Except we have to specify the maximum size of string because char is a primitive data type of C++.
Code C++
char line[100]; cin.getline(line, 100);
Using gets
Systax: char * gets( char * s);
“Reads characters from stdin and stores them as a C string into s until a newline character or the end-of-file is reached”
The newline character is not copied to s.
This function is unsafe because it does not have size checking, when the size of input string is equal or greater than the size we declare, it causes buffer overflow.
Code C
char line[100]; // contains maximum 99 characters gets(line); // the size of input string should <= 99
Using fgets
Syntax: char * fgets(char * str, int num, FILE * stream);
“Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached”.
The newline character is copied to str. So this function is quite not comfortable to use when the actual size of the string has 1 more character than you expect.
But it’s safer than gets because it has size cheking.
Code C
char line[100]; fgets(line, 100, stdin);
Conclusion: should use getline
Happy coding