Reputation: 39
I've been working with data written in .txt files and so had some problems.
Example of data: lettts ddo ttttthis
Example of answer: le3ts 2do 5this
I've tried to read 2 times information while second time ignoring first character and below the read function compare with for loop if(char1==char2) count++;
But all it does is making all chars equal.
Any suggestions how to compare chars properly?
#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;
}
Upvotes: 0
Views: 148
Reputation: 40145
#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;
}
Upvotes: 2
Reputation: 750
Ok so maybe this. I don't know you want data from file
#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;
}
Upvotes: 0
Reputation: 9
Fflush solution
You need to do. This will clear the buffer for both standard out and standard in "fflush(null)"
Understanding the need for fflush() and problems associated with it
Upvotes: -1
Reputation: 750
Maybe something like this?
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 );
}
Upvotes: 0