如何在不使用数组的情况下计算C中的相同字符

时间:2014-10-25 10:24:21

标签: c char

我一直在处理用.txt文件编写的数据,因此遇到了一些问题。

Example of data: lettts ddo ttttthis
Example of answer: le3ts 2do 5this

我尝试读取2次信息,而第二次忽略第一个字符并且读取函数低于for循环if(char1==char2) count++;但它所做的只是使所有字符相等。 有关如何正确比较字符的任何建议吗?

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

int main()
{
  char ch,ch2,chvoid;
  int i,num=0,num2=0;
  FILE *fp;

  if (fp = fopen("file.txt", "r"))
  {
    while (ch != EOF)
    {
      ch = getc(fp);
      printf("%c", ch);
    }
    fclose(fp);
  }

  if (fp = fopen("file.txt", "r"))
  {
    chvoid = getc(fp);
    while (ch2 != EOF)
    {
      ch2 = getc(fp);
      printf("%c", ch2);
      num++;
    }
    fclose(fp);
  }
  for(i=1;i<num;i++){
    if(ch!=ch2){
      printf("test");
    }                 
    if(ch==ch2){
      num2++;     
      printf("%d ",num2);
    }       
    num2=0; 
  }
  return 0;
}

4 个答案:

答案 0 :(得分:2)

#include <stdio.h>

int main(void){
    FILE *fp;
    int ch, ch2, count;

    if(NULL==(fp = fopen("file.txt", "r"))){
        perror("file can not open.");
        return 1;
    }
    printf("Example of data: ");
    while((ch=fgetc(fp)) != EOF){
        putchar(ch);
    }
    putchar('\n');
    rewind(fp);

    printf("Example of answer: ");
    count = ch2 = 0;
    while(1){
        ch=fgetc(fp);
        if(ch2 != ch){
            if(count > 1)
                printf("%d", count);
            ch2 && putchar(ch2);//if(ch2)putchar(ch2);
            if(ch == EOF)
                break;
            count = 1;
            ch2 = ch;
        } else {
            ++count;
        }
    }
    fclose(fp);
    return 0;
}

答案 1 :(得分:0)

也许是这样的?

    while( data[i] != '\0' )
    {
        char c = data[i++];
        int counter = 1;

        while( c == data[i] )
        {
            counter++;
            i++;
        }

        if( counter - 1 )
            printf( "%d", counter );

        printf( "%c", c );
    }

答案 2 :(得分:0)

好吧也许这个。我不知道你想要文件中的数据

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

int main( )
{
    char ch, ch2, chvoid;
    int i, num = 0, num2 = 0;
    FILE *fp;

    if( fp = fopen( "file.txt", "r" ) )
    {
        while( ch != EOF )
        {
            ch = getc( fp );
            printf( "%c", ch );
        }
        fclose( fp );
    }

    if( fp = fopen( "file.txt", "r" ) )
    {
        int c = getc( fp );

        while( c != EOF )
        {
            int c2 = getc( fp );
            int counter = 1;

            while( c2 == c )
            {
                counter++;
                c2 = getc( fp );
            }

            if( counter - 1 )
                printf( "%d", counter );

            printf( "%c", c );

            c = c2;
        }

        fclose( fp );
    }


    return 0;
}

答案 3 :(得分:-1)

Fflush解决方案

你需要这样做。这将清除“fflush(null)”

中标准输出和标准的缓冲区

Understanding the need for fflush() and problems associated with it