c - 使用 fgets() 后查找字符串长度

标签 c fgets strlen

我试图找到字符串1(s1)的长度..但它给出的值是0,并且输入s1 =“HELLO”,因为这个错误无法执行我所在的for循环使用字符串1的长度。

以下是代码...在 gcc 版本 4.9.1(Ubuntu 4.9.1-16ubuntu6)中工作正常,但在在线编译器(gcc 4.9.2,C99 标准)中工作正常

/*To check if common characters are present in two strings*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdio_ext.h>
#define SIZE 100
int main() {
int m, i, j, t, len1;
char *s1, *s2;
scanf("%d", &t);  //No. test cases
__fpurge(stdin);

for(m = 0; m < t; m++)
{
    int res = 0;

    s1 = (char *)malloc( SIZE * sizeof( char ));
    s2 = (char *)malloc( SIZE * sizeof( char ));

    fgets(s1, SIZE, stdin);
    fgets(s2, SIZE, stdin);

    *(s1 + strlen(s1) - 1) = '\0';
    *(s2 + strlen(s2) - 1) = '\0';

    len1 = strlen(s1); // len1 is storing as 0
    printf("%d", len1 ); 
    for (i = 0; i < strlen(s1); i++)  
    {
        for (j = 0;j < strlen(s2); j++)
        {
            if ( *(s1 + i) == *(s2 + j) )
            res = 1;
        }
    }

if(res == 1)
printf( "YES\n" );
else
printf("NO\n");
}
return 0; 
}

最佳答案

有一种相当标准的方法来处理使用 fgetsgetline 从文件读取后从输入中剥离换行符。有一些变体,但都用空终止字符替换换行符。这是使用您的代码的示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 64

int main (void) {

    char *s1 = NULL;
    char *s2 = NULL;
    size_t len1 = 0;
    size_t len2 = 0;

    s1 = malloc (SIZE * sizeof *s1);
    s2 = malloc (SIZE * sizeof *s2);

    printf ("\n Enter s1: ");
    fgets (s1, SIZE, stdin);
    printf ("\n Enter s2: ");
    fgets (s2, SIZE, stdin);

    /* strip newline or carriage rtn    */
    len1 = strlen (s1);
    while (len1 > 0 && (s1[len1-1] == '\n' || s1[len1-1] == '\r'))
        s1[--len1] = 0;

    len2 = strlen (s2);
    while (len2 > 0 && (s2[len2-1] == '\n' || s2[len2-1] == '\r'))
        s2[--len2] = 0;

    printf ("\n  len1 : %zu   s1 : %s\n  len2 : %zu   s2 : %s\n\n", len1, s1, len2, s2);

    if (s1) free (s1);
    if (s2) free (s2);

    return 0;
}

输出

$ ./bin/fgets_strip

 Enter s1: This is s1

 Enter s2: This is s2

  len1 : 10   s1 : This is s1
  len2 : 10   s2 : This is s2

关于c - 使用 fgets() 后查找字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29305821/

相关文章:

c - 在 C 中重新实现 split 函数

c++ - 如何处理: redeclaration of C++ built-in type ‘char16_t’

c - Sizeof 与 Strlen

c - 为什么机器代码操作系统中的可执行文件依赖?

c - 当我的 fgets 输入超过指定的缓冲区大小时,我的(非常简单的)程序似乎表现出奇怪的行为

c - 为什么在c中以如此奇怪的顺序执行代码?

c - scanf 之后 fgets 不起作用

c++ - 如何知道两个 C 字符串是否指向一个内存块?

西里尔字符串的 Php 长度使其值加倍

c - 使用 openssl 库验证自签名/过期证书不会返回错误