I want to do a code that searches a txt file and returns the number of different words and how many times they appear on the text.
I' trying to do that, but I'm having a problem on comparing the word read from the input with the words already read. So I'm doing a code that adds a word to the vector of words if is new, and if it isn't, it increments by 1 the word count. But when I'm comparing the words, it doesn't states that they're equal even when they aren't.
By exemple: txt is filled with:
test test test.
test test test.
("test." =/= from "test"). And it return 7 different words with 3 being NULL, "3 test" and 1 "test." . That should return 2 words and count 4 on test and count 2 on test.
Can anybody see what is wrong with my code?
#define MAX_PALAVRAS 1024
#define MAX_TAM_PALAVRA 32
typedef struct ocorrencia_ {
char palavra[MAX_TAM_PALAVRA];
int pos;
int num_ocorrencias;
}ocorrencia;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main (int argc, char * argv[]){
ocorrencia palavras[MAX_PALAVRAS];
int i,palavras_diferentes=0,palavra_atual=0;
char aux[MAX_TAM_PALAVRA];
bool nova_palavra=true;
for (i=0;i<MAX_PALAVRAS;i++){
palavras[i].pos=-1;
palavras[i].num_ocorrencias=0;
}
FILE * D = fopen("input.txt","r");
while (!feof(D)){
char aux2[MAX_TAM_PALAVRA];
fscanf(D,"%s",aux);
for (i=0;i<palavras_diferentes;i++){
if (strcmp(palavras[palavras_diferentes].palavra,aux)==0){
nova_palavra=false;
break;
}
palavra_atual++;
}
if (nova_palavra){
strcpy(palavras[palavra_atual].palavra,aux);
palavras_diferentes++;
}
palavras[palavra_atual].num_ocorrencias++;
printf("%s\n",palavras[palavra_atual].palavra);
}
fclose (D);
printf("diferent words=%i\n",palavras_diferentes);
printf("success!\n");
return (EXIT_SUCCESS);
}
Thanks for taking or time reading or trying to help!
Following my comments, here are a few changes that may help you :
-Set palavra_atual to 0 and nova_palavra to true at the beginning of the while loop.
-Test the return of fscanf, add something like if(fscanf(D,"%s",aux)==1){...}
-Test all words ! if (strcmp(palavras[i].palavra,aux)==0)
Here goes the code :
#define MAX_PALAVRAS 1024
#define MAX_TAM_PALAVRA 32
typedef struct ocorrencia_ {
char palavra[MAX_TAM_PALAVRA];
int pos;
int num_ocorrencias;
}ocorrencia;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main (int argc, char * argv[]){
ocorrencia palavras[MAX_PALAVRAS];
int i,palavras_diferentes=0,palavra_atual=0;
char aux[MAX_TAM_PALAVRA];
bool nova_palavra=true;
for (i=0;i<MAX_PALAVRAS;i++){
palavras[i].pos=-1;
palavras[i].num_ocorrencias=0;
}
FILE * D = fopen("input.txt","r");
while (!feof(D)){
palavra_atual=0;
nova_palavra=true;
char aux2[MAX_TAM_PALAVRA];
if(fscanf(D,"%s",aux)==1){
for (i=0;i<palavras_diferentes;i++){
if (strcmp(palavras[i].palavra,aux)==0){
nova_palavra=false;
break;
}
palavra_atual++;
}
if (nova_palavra==true){
printf("new word %d %s\n",palavra_atual,aux);
strcpy(palavras[palavra_atual].palavra,aux);
palavras_diferentes++;
}
palavras[palavra_atual].num_ocorrencias++;
printf("%s\n",palavras[palavra_atual].palavra);
}
}
fclose (D);
printf("diferent words=%i\n",palavras_diferentes);
printf("success!\n");
return (EXIT_SUCCESS);
}
You will be interesseted by ispunct() of ctypes.h here
Related
I don't get an error but when I do run the program it repeats what I stated
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define strsize 25
void cap(char *str_cap);
int main()
{
char str[strsize];
printf("enter a word with less than 25 letters\n---->");
gets(str);
cap(str);
I tried using toupper in printf but that did not work either
also I am not sure how to isolate the first letter
printf("%s",str,1);
return 0;
}
void cap(char *str_cap)
{
if(islower(str_cap) || isupper(str_cap))
toupper (str_cap);
(str_cap,1);
}
It is good if functions return value.
You ask for the first letter not first char in the string which makes a difference when you want to convert " hello".
Check for the error conditions.
char *cap(char *str_cap)
{
char *saved = str_cap;
if(*str_cap)
{
while(*str_cap && !isalpha((unsigned char)*str_cap))
{
str_cap++;
}
if(*str_cap) *str_cap = toupper((unsigned char)*str_cap);
}
return saved;
}
Just calling toupper() is not going to change the string's first character to uppercase. You have to set the first character of the string explicitly.
Have a look at the following implementation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define strsize 25
void cap(char *str_cap);
int main()
{
char str[strsize];
printf("enter a word with less than 25 letters\n---->");
fgets(str, strsize, stdin);
cap(str);
printf("%s",str);
return 0;
}
void cap(char* str_cap)
{
int length = strlen(str_cap);
for(size_t i=0;i<length;i++){
if(isalpha(str_cap[i])){
if(islower(str_cap[i])){
str_cap[i] = toupper(str_cap[i]);
}
break;
}
}
}
Input:
andy baker
Output:
---->Andy baker
Fairly new to C, I am trying to read a file of multiple words using bash indirection, and put the words into a string array. The end of the file is marked with a -1.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void init(char* words[]);
int main(int argc,char *argv[]){
char* words[400000];
init(words);
int i = 0;
do{
printf("%s",words[i]);
i++;
}while(!strcmp(words[i],"-1"));
}
void init(char* words[]){ // initializes array
int i = 0;
do{
fgets(words[i],1024,stdin);
i++;
}while(!strcmp(words[i],"-1"));
}
This gives me a segmentation fault, if any other information is needed I'm more than happy to provide it.
If I guessed correctly, '400000' means the max lines the user can input. But the default size of stack on Windows OS is 1M, sizeof(void*) * 400000 = 1,600,000...
The other thing is that you have not allocated memory for every line.
So, I try to correct your code like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LINE 4000 // '400000' is really too big!
void init(char* words[]);
int main(int argc,char *argv[]){
char* words[MAX_LINE];
memset(words, 0 , sizeof(words));
init(words);
int i = 0;
do{
printf("%s",words[i]);
delete words[i];
words[i] = nullptr;
i++;
}while(!strcmp(words[i],"-1"));
}
void init(char* words[]){ // initializes array
int maxLen = 1024;
int i = 0;
do{
words[i] = new char[maxLen];
memset(words[i], 0, maxLen);
fgets(words[i], maxLen, stdin);
i++;
}while(!strcmp(words[i],"-1") && i < MAX_LINE);
}
For my OS class, I need to print out the result of this matrix multiplication using only system calls. Following my lecture notes, I wrote up this piece of code. I use :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 1000
// Matrix
long long int A[N][N],B[N][N],R[N][N];
int main(int argc, char *argv[])
{
int x,y,z;
char str[100];
/* Matrix inicialization */
for(y=0;y<N;y++)
for(x=0;x<N;x++)
{
A[y][x]=x;
B[y][x]=y;
R[y][x]=0;
}
/* Matrix multiplication */
for(y=0;y<N;y++)
for(z=0;z<N;z++)
for(x=0;x<N;x++)
{
R[y][x]+= A[y][z] * B[z][x];
}
//System calls for printing the result
sprintf(str,"%lld\n",R);
write(1,str,strlen(str));
exit(0);
}
Now, it's printing a just a 14295680 in the console. The professor gave us a file with machine code and it's printing 332833500, which seems more reasoneable.
Thanks in advance.
Edit: changed type on the printf call
Edit2: fix R[N][N]
Just replace the sprintf value:
sprintf(str,"%lld\n",R[N-1][N-1]); // = 332833500
write(1,str,strlen(str));
instead of
sprintf(str,"%lld\n",R); // this is a pointer
write(1,str,strlen(str));
I'm a begginer but I'm basically creating a program that opens a binary file containing 'parts' structure, reads the structure
into an array, sets the on_hand member of each structure to 0, and then writes the structure back to the file. Here's my code:
invclear.c
/* Modifies a file of part records by setting the quantity
on hand to a zero for all records */
#include <stdio.h>
#include <stdlib.h>
#define NAME_LEN 25
#define MAX_PARTS 100
struct part { //size= 36 bytes (2 holes in between number and name[] array
int number;
char name[NAME_LEN+1];
int on_hand;
}inventory[MAX_PARTS];
int num_parts;
int main()
{
FILE *fp;
int i;
if((fp=fopen("clear_sample.c", "rb+")) == NULL)
{
fprintf(stderr, "Can't open inventory file.\n");
exit(EXIT_FAILURE);
}
num_parts = fread(inventory, sizeof(struct part), MAX_PARTS, fp); //reads the contents
for(i=0; i<num_parts; i++)
inventory[i].on_hand=0; //clears them
rewind(fp); //sets file position at beggining
fwrite(inventory,sizeof(struct part), num_parts, fp);
fclose(fp);
return 0;
}
clear_sample.c
#include <stdio.h>
#include <stdlib.h>
#define NAME_LEN 25
#define MAX_PARTS 100
struct part {
int number;
char name[NAME_LEN+1];
int on_hand;
}inventory[MAX_PARTS]={0};
int main()
{
int i;
int num_parts;
for(i=1;i<=15;i++)
inventory[i].on_hand=i;
for(i=1;i<=15;i++)
printf("%d\n",inventory[i].on_hand);
return 0;
}
It runs without errors but unfortunately it's not clearing the on_hand variable to 0, in fact it's deleting almost the whole file. This is the modified clear_sample.c file that I get:
#include <stdio.h>
#include <st
Any ideas into why am I doing wrong would be greatly appreciated.
You have been misled by whatever tool you used to inspect the resulting file. It is not
#include <stdio.h>
#include <st
In fact it is
#include <stdio.h>
#include <std^#^#^#^#h>
#define NAME_LEN 25
#define ^#^#^#^#PARTS 100
struct part {
int^#^#^#^#ber;
char name[NAME_LEN+1];
^#^#^#^#int on_hand;
}inventory[MAX_^#^#^#^#S]={0};
int main()
{
int i^#^#^#^# int num_parts;
for(i=1;i<^#^#^#^#i++)
inventory[i].on_han^#^#^#^#
for(i=1;i<=15;i++)
^#^#^#^#ntf("%d\n",inventory[i].on_hand)^#^#^#^# return 0;
}
All those ^# are binary zero bytes, corresponding to zeroes you've put into on_hand.
As mentioned in comments, to test your program prepare a file which does obey the format you expect.
This function is supposed to get a parameter as the pointer of a file and put all file into the struct anagram, then write it to another file. Right now the data only contains a.word, but it suppose to containst a.sorted too? I have check the a.sorted using printf
and it printf out the correct data, but why its not writing to the data file?
It still cant get the a.sorted even if i increase the count of the frwite
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include "anagrams.h"
#define SIZE 80
//struct
struct anagram {
char word[SIZE];
char sorted[SIZE];
};
void buildDB ( const char *const dbFilename ){
FILE *dict, *anagramsFile;
struct anagram a;
//check if dict and anagram.data are open
errno=0;
dict= fopen(dbFilename, "r");
if(errno!=0) {
perror(dbFilename);
exit(1);
}
errno=0;
anagramsFile = fopen(anagramDB,"wb");
char word[SIZE];
char *pos;
int i=0;
while(fgets(word, SIZE, dict) !=NULL){
//get ripe of the '\n'
pos=strchr(word, '\n');
*pos = '\0';
strncpy(a.word,word,sizeof(word));
//lowercase word
int j=0;
while (word[j])
{
tolower(word[j]);
j++;
}
/* sort array using qsort functions */
qsort(word,strlen(word), 1, charCompare);
strncpy(a.sorted,word,sizeof(word));
//printf(a);
fwrite(&a,1,strlen(word)+1,anagramsFile);
i++;
}
fclose(dict);
fclose(anagramsFile);
}
it suppose to contains data with a.sorted for example "10th 01ht"
data:
fwrite(&a,1,strlen(word)+1,anagramsFile); should have been fwrite(a.sorted,1,strlen(a.sorted)+1,anagramsFile); I assume the declaration of sorted as char sorted[SOME_LEN];