0
I have a code where I am reading character by character within a file and saving them within an array called "input". I am using a comma (the 44 character of the ASCII table) as the stop character, so I will read the characters of the file and store them all in the "words" vector while I do not find a comma, when I find the comma I stop reading the characters and have an if that compares the content that was already saved in this "input" vector with the words I want to find, for example "pineapple", if the string within my "input" vector equals "pineapple" it presents a prinft on the screen with "I found pineapple" and clears my vector, otherwise it passes to the next if.
I need to make that each time that the character string I have inside my "input" vector equals the character string I’m comparing inside my if I save this string from the "input" vector as the position of a new vector called "new vector". For example: The characters of my file were read and they formed the string "pineapple", I compare this string inside my if and check that it was found, then I need to copy it from the vector "input" as a new position inside the vector "new vector". In this case it should be: vector novo[0] = "pineapple".
That is the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int caractere;
int i=0;
int v=0;
char entrada[100] = "";
char limpa;
FILE *arquivo;
arquivo = fopen("arq.txt", "r");
if (arquivo){
do
{
caractere = fgetc(arquivo);
if(caractere != 44) {
entrada[i++] = caractere;
}else{
if(strcmp(entrada, "abacaxi")==0){
printf("\nEncontrado abacaxi\n", entrada);
for(v=0; v<10; v++)
entrada[v]=limpa;
}else if(strcmp(entrada, "manga")==0){
printf("\nEncontrada manga\n", entrada);
for(v=0; v<10; v++)
entrada[v]=limpa;
}else if(strcmp(entrada, "laranja")==0){
printf("\nEncontrada laranja\n", entrada);
for(v=0; v<10; v++)
entrada[v]=limpa;
}else if(strcmp(entrada, "morango")==0){
printf("\nEncontrado morango\n", entrada);
for(v=0; v<10; v++)
entrada[v]=limpa;
}
for(v=0; v<10; v++)
entrada[v]=limpa;
i=0;
}
}while(!feof(arquivo));
}
system("pause");
}
You do not treat the end of the file. You did not assign anything to the variable
limpa, so it will contain memory junk, which will then assign to your arrays. In reality to clear a string simply move the character ' 0' to the first position of the array, it will be considered a string of length 0.– anonimo