I am trying to count words from file called file.txt but it gives me charecters with whitespace.
How to count words without counting the whitespace?
#include<stdio.h>
#include<conio.h>
main()
{
FILE *f1;
char c;
clrscr();
printf("data output");
f1 = fopen("file.txt","r");
while((c=getc(f1))!=EOF)
{
printf("%c",c);
}
fclose(f1);
getch();
}
Please help me to solve it as soon as possible.
Thanks in advance.
// Create a char array to store a word
char word[100];
// Stop when fscanf returns 0
while(fscanf(f1, "%s", word)==1)
{
// print the word
printf("%s ",word);
// Increment count
count ++;
}
// Print count
printf("%d\n", count );
Remember it assumes that no word is longer than 100 characters since fscanf does't check for buffer overflow
Related
I need to make a program that outputs all lines that contain a matching string "target" and sum up the number of matches along with the total cost,
The problem is that the for loop stops at the first iteration regardless of there being a match
I have tried using strstr() instead of strcmp() and it works, but since this is a school assignment, i cant use strstr()
#include<stdio.h>
#include<string.h>
struct data{
char product[100];
char name[100];
int price;
};
int main(){
FILE *f;
f = fopen("Customers.txt", "r");
int x;
scanf("%d",&x);
struct data arr[x];
for(int i=0;i<x;i++){
fscanf(f,"%[^,], %[^,], %d",arr[i].product,arr[i].name,&arr[i].price);
}
char target[100];
int res;
int count=0;
int total=0;
scanf("%s",target);
for(int j=0;j<x;j++){
res=strcmp(arr[j].product,target);
if(res==0){
printf("%s, %s, %d",arr[j].product,arr[j].name,arr[j].price);
count++;
total = total + arr[j].price;
}
else{
continue;
}
}
printf("\nTotal Buyers: %d\n",count);
printf("Total Amount: %d\n",total);
}
File:
Gem, Alice, 2000
Gold, Bob, 3000
Gem, Cooper, 2000
Input:
3 (No. of lines in the file)
Gem (target)
Expectd output:
Alice 2000
Cooper 2000
The fscanf format string is wrong, it should be:
"%[^,], %[^,], %d\n"
Note the final \n. Without that, the \n (new line) will not be absorbed and the first item of the next string read will start with \n.
Or even better: use this format string:
" %[^,], %[^,], %d"
Note the space at the beginning. With that format string all leading and trailing whitespace, including the newline, will be absorbed.
Furthermore you absolutely need to check if fopen fails, in your case it apparently doesn't, but if the file cannot be opened for some reason, and you do not any checks, the subsequent operations on f wont end well.
So you need at least this:
...
f = fopen("Customers.txt", "r");
if (f == NULL)
{
printf("Can't open file\n");
return 1;
}
...
The program below is supposed to print out all the characters of a line from a file between two entered characters. It works fine for all test cases except for the one where one of the explicitly entered characters is a space.
ex.
Input:
12345 Maja Majovska: 54
15145 Aco Acoski: 95
14785 Martin Martinoski: 87
#
: //Under the hashtag is the space
Correct output:
Maja Majovska
Aco Acoski
Martin Martinoski
My output:
54
15145 Aco Acoski 95
14785 Martin Martinoski 87
#include<stdio.h>
#include<string.h>
void wtf() {
FILE *f = fopen("podatoci.txt", "w");
char c;
while((c = getchar()) != '#') {
fputc(c, f);
}
fclose(f);
}
int main()
{
wtf();
getchar();
char z1, z2, c;
FILE *f;
f=fopen("podatoci.txt", "r");
int flag=0;
scanf(" %c %c", &z1, &z2);
while((c=fgetc(f))!=EOF){
if(c==z1){
flag=1;
continue;
}
if(c==z2){
flag=0;
printf("\n");
}
if(flag)
printf("%c", c);
}
fclose(f);
return 0;
}
Can someone point out simply what am i doing wrong? I'm new to working with files.
I think this code should work. Enter the two characters at the same time #: (# is space) followed by enter
#include<stdio.h>
#include<string.h>
void wtf() {
FILE *f = fopen("podatoci.txt", "w");
char c;
while((c = getchar()) != '#') {
fputc(c, f);
}
fclose(f);
}
int main()
{
// wtf();
// getchar();
char z1, z2, c;
FILE *f;
f=fopen("podatoci.txt", "r");
int flag=0;
printf("enter chars : ");
// scanf(" %c %c", &z1, &z2);
// printf("chars are |%c| |%c|",z1,z2);
char name[3];
fgets(name, 3, stdin);
// printf("chars are |%c| |%c|",name[0],name[1]);
char buffer[512]; // I suppose 512 is enough (see Two problems below)
int i=0;
while((c=fgetc(f))!=EOF){
/* Different problems :
1 : you have a 'space' followed by 'end of line' before ':'
example you have a space before 54 but end of line before :
So you could not display characters when a 'space' is a found.
You have to use a temporary buffer
2 : you have to reset your flag at the end of line
3 : If you have ':' alone, do not printf("\n")
4 : If you have a 'space' after the first 'space', it must be printed
example : Maja Majovska
^ (this space)
*/
if(c=='\n') { // Address pb 2
flag=0;
i=0;
continue;
}
if(!flag&&c==name[0]){ // Address pb 4
flag=1;
continue;
}
if(flag&&c==name[1]){ // Address pb 3
flag=0;
buffer[i]='\0'; // end of string
printf("%s\n",buffer);
i=0;
}
if(flag)
buffer[i++]=c; // Address pb 1
}
fclose(f);
return 0;
}
Some remarks :
Most of the explanations are in the code comments (you could remove it after reading)
I use fgets instead of scanf (https://stackoverflow.com/a/1248017/7462275)
I do it like that to keep the code as close to its original form as possible. But, I think it would be better to get text line by line and use string functions (string.h). For example, to print the first substring between two characters (no sanity checks done : these two characters must be in the string)
while((fgets(buffer,512,f))!=NULL){
i=strchr(buffer,name[0]);
*(strchr(i,name[1]))='\0';
printf("%s\n",i);
}
Using C, I am trying sum up the numbers in a file. The file contains numbers such as:
123
456
788
...
356
When running the code, it properly asks for input and prints the number I enter. However, it does not sum the file, and just displays an unrecognized character symbol, like a small ?. I don't think the number is over the alloted INT_MAX_SIZE. What seems to be the issue?
#include <stdio.h>
main() {
//Number variable to assign each line to
int c;
int fds[2];
int childid;
int size;
int number;
int sum;
printf ("Enter the number of processes to create: ");
scanf ("%d", &number);
printf ("You entered: %d", number);
printf("\n");
//File I/O operations
FILE *file;
//Open file for reading
file = fopen("Project1_OS/project1_data/file1.dat", "r");
//If file is found
if (file) {
//While file has data to be read
while ((c = getc(file)) != EOF)
//Print data
//putchar(c);
sum+=c;
//Close the file I/O
fclose(file);
}
putchar(sum);
}
first getc it's a function for reading characters from a file not integers .
you have to use fscanf :
fscanf(file,"%3d",&c)
second putchar it's a function for printing characters not intgers .
so you have to write :
printf("%d",sum);
I have to write a program to count the number of times a character appears in the File. (Case insensitive... 'a' and 'A' are considered to be the same)
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
FILE *fp1;
char ch,f[100],c,d;
int ct=0;
printf("Enter the file name\n");
scanf("%s",f);
fp1=fopen(f,"r");
printf("Enter character:");
scanf(" %c",&c);
do
{
printf("%c",ch);
ch=fgetc(fp1);
d=toupper(ch);
printf("%c",d);
if(c==d)
++ct;
}while(ch!=EOF);
fclose(fp1);
printf("\n");
printf("%d",ct);
return 0;
}`
This is the program I have written but the output i'm getting it is..
[ a.txt contains the string-
aaa ]
Now when running the program this is the output which I get :
Enter the file name
a.txt
Enter character:a
aAaAa
0
What am I doing wrong here ??
What you need is to check if the character to be searched is equal to a character in the file or its uppercase version and if it is, increment ct.
Simply change
if(c==d)
to
if(c==d || c==ch)
Other problem: ch is not initialized here
printf("%c",ch);
in the first iteration of the do...while loop. Fix it by moving the above printf after
ch=fgetc(fp1);
Also, add a check to see if ch is not EOF before printing it.
If you input 'a', and you transform all your characters toUpper()... It can definitely not work ;:=)
This code works i guess.
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp1;
char c;
char ai,s;
char fname[20];
int count=0;
clrscr();
printf("enter the character to be counted:");
scanf("%c",&ai);
s=toupper(ai);
printf("enter the file name :");
scanf("%s",&fname);
fp1=fopen(fname,"r");
if(fp1==NULL)
{
printf("cannot open this file");
}
do
{
c=fgetc(fp1);
if(c==ai || c==s)
{
count=count+1;
}
}
while(c != EOF);
printf("\nFILE '%s' has %d instances of letter %c",fname,count,ai);
getch();
}
I need to write a function which takes 2 words and count its length. I wrote below one but this code only woks for 1st word. How can I improve it to count whole sentence?
#include <stdio.h>
int findlen(int *s);
int main(void)
{
char string1[80];
printf("Enter a string: ");
scanf("%s", string1);
printf("Lenght of %s is %d\n", string1, findlen(string1));
}
//find the length of the inputted string
int findlen(char *s)
{
int count = 0;
while (*s != '\0')
{
s++;
count++;
}
return count;
}
scanf will take the one word input only.. (i.e) it breaks when space appears..
Try fgets to read the complete string till \n
You can use fgets to safely get the line from your file:
From here:
char *fgets(char *s, int size, FILE *stream);
so replace your scanf line with:
fgets(string1, sizeof(string1), stdin);
If you used gets instead, it doesn't know how large your buffer is and it would crash when reading too large line.
Next, if you want to know a length of your string you could use strlen function from string.h:
#include<string.h>
...
printf("Lenght of %s is %d\n", string1, strlen(string1));
use [%^\n] format specifier so that it will scan the string till '\n' encounter so the problem in scanning string having space(eg. "hello word") will be solved.
scanf("[%^\n]",straddr);