1

I have a file named email.txt, which contains some text. I am trying to split the given string containing spaces into multiple strings. The program I wrote does not split the words into separate lines. It gives me the output of the last word of the file. Here is my code

#include <stdio.h>
#include <string.h>
#define MAXCHAR 1000
int main()
{
    FILE *fp2;    
    char str2[MAXCHAR];
    int line = 0;
    char delim[] = " ";
    int init_size = strlen(str2);
    fp2 = fopen("email.txt","r");
    while( fgets( str2, MAXCHAR, fp2 )) {
        line++;
        // printf(" %s",str2);  
    }
    char *ptr = strtok(str2, delim);
    
    while(ptr != NULL)
    {
        printf("%s\n", ptr);
        ptr = strtok(NULL, delim);
    }       
    
    return 0;
}
sanober
  • 21
  • 5
  • If the domain names are separated by spaces you can use `fscanf(fp2, "%s", str2)` – sebastian Aug 20 '20 at 07:56
  • "The program I wrote is not giving me the desired output. It's not working." This is not a useful problem description. What does it output instead? What input do you provide? What output do you expect for that sample input? – Gerhardh Aug 20 '20 at 08:00
  • You can find solution here https://stackoverflow.com/questions/2523467/how-to-split-a-string-to-2-strings-in-c – I S Aug 20 '20 at 08:05
  • 2
    You do `strlen(str2)` while `str2` is still uninitialized. That leads to *undefined behavior*. – Some programmer dude Aug 20 '20 at 08:10
  • You can use a *String Literal* for `delim`, e.g. `const char *delim = " ";`, but you may also want to add `'\t'` and `'\n'` so if the delimiter is a `tab` your parsing still works and `'\n'` to ensure you trim the `'\n'` from the last domain, e.g. `const char *delim = " \t\n";` – David C. Rankin Aug 20 '20 at 08:14

2 Answers2

1

You are first looping over all the lines in your file, and then you loop over strtok() returns. This means you only ever tokenize the last line read.

You need to nest those loops -- read a line, tokenize, then read the next line.

while( fgets( str2, MAXCHAR, fp2 )) {
    char * ptr;
    line++;
    //  printf(" %s",str2);
    ptr = strtok(str2, delim);

    while(ptr != NULL)
    {
        printf("%s\n", ptr);
        ptr = strtok(NULL, delim);
    }
}
DevSolar
  • 67,862
  • 21
  • 134
  • 209
0

You could just iterate over all the characters and then output either

  • the character you just read or
  • if the character is a space, a newline character
Finn
  • 326
  • 3
  • 11