Home  >  Article  >  Backend Development  >  How to use gets function in c++

How to use gets function in c++

下次还敢
下次还敢Original
2024-05-01 11:30:30613browse

The gets() function in C is used to read a string from standard input and store it in a character array. It reads the string until a newline character is encountered or the end of file is encountered. Its usage includes: declaring a character array to store strings. Use the gets() function to read the string. Verify the return value to ensure the read was successful.

How to use gets function in c++

Usage of gets() function in C

gets() function is used to read characters from standard input string and store it in the specified character array. It is similar to the scanf() function, but has no format specifier and reads until a newline character is encountered or the end of file is encountered.

Syntax:

<code class="cpp">char *gets(char *str);</code>

Parameters:

  • str: ​​ points to the character array Pointer to store the read string.

Return value:

  • Returns a pointer to the character array when the string is successfully read.
  • Return NULL when the end of file is encountered.

Usage:

To use the gets() function, follow these steps:

  1. Declare a character array whose Large enough to hold the string to be read.
  2. Use the gets() function to read a string from standard input.
  3. Verify the return value to ensure the read was successful.

Example:

<code class="cpp">#include <iostream>

using namespace std;

int main() {
  char str[100];

  cout << "Enter a string: ";
  gets(str);

  if (str != NULL) {
    cout << "The string you entered is: " << str << endl;
  } else {
    cout << "Error reading the string." << endl;
  }

  return 0;
}</code>

Note:

  • gets() function does not check the buffer overflow, so care must be taken when reading strings.
  • For user input, it is recommended to use safer input functions such as getline() or fgets().
  • gets() function does not remove newlines, so you need to manually remove it when using it.

The above is the detailed content of How to use gets function in c++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn