user3625236
user3625236

Reputation: 61

C Prints symbols then reading from file instead of characters

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

Read from file and print c value

void skaitymas()
{
 FILE *fp = fopen("3.txt","r");
 int c,a;
 while((c=getc(fp))!=EOF)
 {

   if(c != ' ')
   {
   a = a + c; 
   printf("%c ",a);
   if(c == '\n')
   printf("\n");
   }
 }

}

Main

int main()
{
skaitymas();
printf("\n");
system("pause");
}

Input file

zodis antis plastake zvirblis aksesuaras

kompiuteris pelyte kate afganistanas lietuva

Explanation

So I am trying to read words from file and print them out but it prints symbols instead of character. I guess printf("%c",a) is a problem here how can I solve it?

Upvotes: 0

Views: 480

Answers (4)

Younggun Kim
Younggun Kim

Reputation: 986

a = a + c is actual sum up a and c value so it represent integer value.

To concatenate two character, use sprintf(). Or, append a char to a string buffer:

char buf[BUF_SIZE]; // string buffer [snip] buf++ = a; // append a char to string buffer and increment buf pointer by 1byte.

Upvotes: 0

smagnan
smagnan

Reputation: 1267

Why don't you use

char a,c; // characters

instead of

int a,c;  // integers

And I don't get why you use a instead of just printing c

printf("%c",c);

Moreover, you loop on:

a = a + c;

So it adds the ascii value and do not concatenate (you will quickly read garbage, after some loops) (if you vant to concateate a and c can't be ints or chars, or they can but the concatenation will be difficult and you will have to use more vars)

Upvotes: 0

vaibhav
vaibhav

Reputation: 396

Run it, working now :

#include <stdio.h>

void skaitymas()
{
 FILE *fp = fopen("3.txt","r");
 char c,a='\0';
 while((c=getc(fp))!=EOF)
 {

   if(c != ' ')
   {
   //a = a + c;
   printf("%c ",c);
   if(c == '\n')
   printf("\n");
   }
 }

}

int main()
{
skaitymas();
printf("\n");
system("pause");
}

Upvotes: 1

DexTer
DexTer

Reputation: 2103

What is

a = a + c;

This will print first character correct but then add value of 'o'(111) in value of 'z'(122) and it keep on doing same which may overflow normal char limits, hence it prints symbols.

Edit : As you have not even initialized variable 'a', it may contain garbage value so it won't even print first character correct.

Upvotes: 0

Related Questions