Home >Backend Development >C#.Net Tutorial >How to enter a string with spaces in C language

How to enter a string with spaces in C language

下次还敢
下次还敢Original
2024-05-02 19:09:17885browse

In C language, use gets(), fgets() and scanf() functions to input strings containing spaces. gets() reads until newline or EOF, fgets() requires a file pointer to be specified, and scanf() uses the %1%*c format specifier to read until newline. \n ↩

How to enter a string with spaces in C language

How to input a string containing spaces in C language

In C language, you can use The following method inputs a string containing spaces:

Method 1: Use gets() function

<code class="c">char str[100];
printf("请输入一个包含空格的字符串:");
gets(str);</code>

Method 2: Use fgets() function

<code class="c">char str[100];
FILE *fp = fopen("input.txt", "r");
if (fp == NULL) {
    perror("打开文件失败");
    return -1;
}
fgets(str, 100, fp);
fclose(fp);</code>

Method 3: Use scanf() function

<code class="c">char str[100];
printf("请输入一个包含空格的字符串:");
scanf("%[^\n]%*c", str);</code>

Note:

  • Use gets() function, be aware that it reads input until it encounters a newline character or EOF, so this may cause problems if the input string is very long.
  • When using the fgets() function, you need to specify the file pointer.
  • When using the scanf() function, you need to use the %1%c format specifier, where %2 will read until a newline character is encountered, %c will skip the newline character.

  1. \n
  2. \n

The above is the detailed content of How to enter a string with spaces in C language. 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