Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,265 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,500 people online right now. Registration is fast and FREE... Join Now!




Writing a program to split a text file into words? im having problems

 
Reply to this topicStart new topic

Writing a program to split a text file into words? im having problems

andypaterson40
6 Nov, 2006 - 12:12 PM
Post #1

New D.I.C Head
*

Joined: 6 Nov, 2006
Posts: 1


My Contributions
CODE
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

int main()
{
    FILE *p;
    int numOfWords;
    char word;
    numOfWords = 0;
    word = getchar();
    p = fopen("words.txt", "wt");
    if(p != NULL)
    {
               fputs("fopen example", p);
               fclose(p);
    }
    return 0;
}


edit: added [code] tags ~ jayman9
User is offlineProfile CardPM
+Quote Post

horace
RE: Writing A Program To Split A Text File Into Words? Im Having Problems
6 Nov, 2006 - 01:19 PM
Post #2

D.I.C Addict
Group Icon

Joined: 25 Oct, 2006
Posts: 573



Thanked: 4 times
Dream Kudos: 50
My Contributions
you have opened a file and then written the text "fopen example" to it OK.

from your title "Writing a program to split a text file into words" it sounds more like you need to open a file, read text from it and count the words read.

This modified version of your program, which reads a word from a file and prints it, should help you get started
CODE

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *p;
int numOfWords;
char word[20];
numOfWords = 0;

p = fopen("words.txt", "rd");
if(p != NULL)
{
fscanf(p," %s",word);    // read a word (stops at next white space)
printf("%s", word);
fclose(p);
}
return 0;
}

the statement
fscanf(p," %s",word);
skips leading 'white space' (spaces and new lines), reads characters into word[] stopping at next 'white space'.
put this in a loop and count the words read until end of file

This post has been edited by horace: 6 Nov, 2006 - 01:20 PM
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/4/08 07:23PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month