I need to print all phrases from a file (phrases can end in '.', '?' or '!')
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* read_file(char *name) {
FILE *file;
char *text;
long num_bytes;
file = fopen(name, "r");
if(!file) {
printf("File could not be opened!");
exit(EXIT_FAILURE);
}
fseek(file, 0, SEEK_END);
num_bytes = ftell(file);
fseek(file, 0, SEEK_SET);
text = (char*) malloc(num_bytes * sizeof(char));
fread(text, 1, num_bytes, file);
fclose(file);
return text;
}
int main(int argc, char* argv[]) {
char *text = read_file(argv[1]);
unsigned int count = 0, index=0;
char *line = (char*) malloc(sizeof(text));
for(int i = 0; i < strlen(text); i ) {
line[index] = text[i];
index ;
if(text[i] == '.' || text[i] == '?' || text[i] == '!') {
count ;
printf("[%d] %s\n", count, line);
memset(line, 0, index 1);
index = 0;
}
}
return EXIT_SUCCESS;
}
I have this piece of code that kind of works but if my file as the following text: "My name is Maria. I'm 19." the second phrase is printed with a ' ' in the beggining. Can someone please help finding a way to ignore those spaces? Thank you
CodePudding user response:
You can test for a whitespace character by comparing the char in question to ' '.
if(text[i] == ' ')
// text[i] is whitespace
CodePudding user response:
One possible solution, advance to the next non-whitespace character when you find the end of the sentence. You also need to make sure you've malloc
d enough memory for the current phrase:
#include <ctype.h> // for isspace
...
size_t textLength = strlen(text);
// malloc based on the text length here, plus 1 for the NUL terminator.
// sizeof(text) gives you the size of the pointer, not the size of the
// memory block it points to.
char *line = malloc(textLength 1);
for(size_t i = 0; i < textLength; i ) {
line[index] = text[i];
index ;
if(text[i] == '.' || text[i] == '?' || text[i] == '!') {
count ;
printf("[%d] %s\n", count, line);
memset(line, 0, index 1);
index = 0;
// advance to the next non-whitespace char
do
{
// advance to the next char (we know the current char is not a space)
i ;
// keep advancing i while the next char is in range of the
// text and the next char is a space.
}while (i 1 < textLength && isspace(text[i 1]) != 0);
}
}
Output:
[1] My name is Maria.
[2] I'm 19.
There's also no need to cast the return value of malloc