从fgets()输入中删除尾部换行符
fgets()从指定的数据流中读取一行,并将其存储到str指向的字符串中。当读到**(n - 1)**个字符、读到换行符或到达文件末尾时(以先到者为准),它就停止。
然而,fgets()也会读取尾部换行符,并最终返回数据字符串,后面是**'/n'。因此,在这篇文章中,我们将看到一些从fgets()**输入中移除尾部换行符的方法。
从fgets()输入中删除尾部换行符的方法
方法1(使用 strcspn() 函数)。
这是一个C语言库函数,用于计算两个字符串中第一次出现的字符之前的字符数的长度。
语法。
str [ strcspn (str, "\n")] = 0;
参数:
str:使用fgets()存储数据的字符串,即(char *fgets(char *str, int n, FILE *stream))
"\n"。应该计算长度的字符
因为我们已经给了**"\n "作为第二个字符串,所以我们将得到"\n "之前的字符串的长度。**现在把'\0'放在'\n'的位置上
下面是实现方法。
C
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 15
int main()
{
char str[BUFFER_SIZE];
printf("Enter the data = ");
if (fgets(str, sizeof(str), stdin) == NULL) {
printf("Fail to read the input stream");
}
else {
str[strcspn(str, "\n")] = '\0';
}
printf("Entered Data = %s\n", str);
return 0;
}
输出。
Enter the data =
Geeks
For
Geeks
Entered Data = Geeks
方法2(使用 strlen() 函数)。
在这个方法中,我们将使用**strlen()函数来确定使用fgets()**进行数据输入的字符串的长度,并且我们将手动将结尾处的char改为null。
下面是实现方法。
C
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 15
int main()
{
char str[BUFFER_SIZE];
printf("Enter the data = ");
if (fgets(str, sizeof(str), stdin) == NULL) {
printf("Fail to read the input stream");
}
else {
str[strlen(str)] = '\0';
}
printf("Entered Data = %s\n", str);
return 0;
}
但是,如果 fgets()读取的文件是一个二进制文件或者读取的第一个字符是空的,这个方法可能会出现问题。因为在这种情况下,strlen(str)会返回0。
方法3(使用strchr()函数)。
在这个方法中,我们将使用 strchr()函数将str中的**"\n "替换为null**,如果字符串中存在"\n "的话。
下面是实现方法。
C
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 15
int main()
{
char str[BUFFER_SIZE];
printf("Enter the data = ");
if (fgets(str, sizeof(str), stdin) == NULL) {
printf("Fail to read the input stream");
}
else {
// find new line
char* ptr = strchr(str, '\n');
if (ptr) {
// if new line found replace with null character
*ptr = '\0';
}
}
printf("Entered Data = %s\n", str);
return 0;
}