Home >Backend Development >C#.Net Tutorial >How to enter a string with spaces in C language
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 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:
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!