Reading word by word from a file in c

In this article, we are going to learn How to Read text File word by word in C. We will read each word from the text file in each iteration.

C fscanf Function


The fscanf() function is available in the C library. This function is used to read formatted input from a stream. The syntax of the fscanf function is:

Syntax

int fscanf(FILE *stream, const char *format, ...)

Parameters :

  • stream − This is the pointer to a FILE object that identifies the stream.
  • format − This is the C string that contains one or more of the following items − Whitespace character, Non-whitespace character, and Format specifiers.
  • A format specifier will be as [=%[*][width][modifiers]type=].

1. Read File Word by Word in C using fscanf Function


Here we are making use of the fscanf function to read the text file. The first thing we are going to do is open the file in reading mode. So using fopen() function and “r” read mode we opened the file. The next step is to find the file stats like what is the size of the data this file contains. so we can allocate exact memory for the buffer that is going to hold the content of this file. We are using the stat() function to find the file size.

  • Once we have the size and buffer allocated for this size, we start reading the file by using the fscanf() function.
  • We keep reading the file word by word until we reach the end of file.In fscanf function, we are passing “%39[^-n] as the argument so we can read the text until we find the next word.
  • The code will look like this:
fscanf(in_file, "%39[^-n]", file_contents)

C Program to Read text File word by word


To run this program, we need one text file with the name Readme.txt in the same folder where we have our code.The content of the file is:

Hello My name is 
John 
danny
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

const char* filename = "Readme.txt";

int main(int argc, char *argv[])
{
    FILE *in_file = fopen(filename, "r");
    if (!in_file) 
	{
        perror("fopen");
        return 0;
    }

    struct stat sb;
    if (stat(filename, &sb) == -1) 
	{
        perror("stat");
        return 0;
    }

    char *file_contents = malloc(sb.st_size);

    while (fscanf(in_file, "%[^-n ] ", file_contents) != EOF) {
      printf("> %sn", file_contents);
	  }
    
	

    fclose(in_file);
    return 0;
}

Output

Hello
My
name
is
John
danny

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Given a text file, extract words from it. In other words, read the content of file word by word. Example : 

    Input: And in that dream, we were flying.
    Output:
    And
    in
    that
    dream,
    we
    were
    flying.

    Recommended: Please try your approach on {IDE} first, before moving on to the solution.

    Approach : 1) Open the file which contains string. For example, file named “file.txt” contains a string “geeks for geeks”. 2) Create a filestream variable to store file content. 3) Extract and print words from the file stream into a string variable via while loop. 

    CPP

    #include <bits/stdc++.h>

    using namespace std;

    int main()

    {

        fstream file;

        string word, t, q, filename;

        filename = "file.txt";

        file.open(filename.c_str());

        while (file >> word)

        {

            cout << word << endl;

        }

        return 0;

    }

    Output:

    geeks
    for
    geeks.

    Time Complexity: O(N) // going through the entire file

    Auxiliary Space: O(1)

    Like Article

    Save Article

    • Remove From My Forums
    • Question

    • how i read from txt file, word by word witout to read all line?

    Answers

    • Okay then. 

      The short answer is that you can’t read word for word in C#.  So you have two options:

      1. Read line by line and split.
      2. Read character by character and find the splitting characters.

      You have examples of the former.  For the latter, you may want to do something like this. (You’ll probably have to modify this to your liking).

      string filename = @»C:filename.txt»;

      using (StreamReader r = new StreamReader(filename))
      {
          string s = string.Empty;
          int i = 0;
          while ((i = r.Read()) != -1)
          {
              Char c = Convert.ToChar(i);
              if (Char.IsDigit(c) || Char.IsLetter(c))
              {
                  s = s + c;
              }
              else
              {
                  if (s.Trim() != string.Empty)
                      Console.WriteLine(s);
                  s = string.Empty;
              }
          }
      }

      The long and the short of this is, though, that reading the file line by line is the simplest method to accomplish this, and reading it character by character is an extremely complex solution.


      David Morton — http://blog.davemorton.net/

      • Marked as answer by

        Friday, May 8, 2009 3:37 PM

    A file is a repository of data that is stored in a permanent storage media, mainly in secondary memory. In order to use the files we should learn how to read information from a file and how to write information into a file.

    A very important concept in C is the stream.The stream is a common logical interface to the various devices( files).A stream is linked to a file while using an open operation. A stream is disassociated from a file while using a close operation. The current location, also referred to as the current position, is the location in a file where the next file access will occur.There are two types of streams text and binary.

    The following are some difference between text and binary files

    • Text file is human readable because everything is stored in terms of text. In binary file everything is written in terms of 0 and 1, therefore binary file is not human readable.
    • A newline(n) character is converted into the carriage return-linefeed combination before being written to the disk. In binary file, these conversions will not take place.
    • In text file, a special character, whose ASCII value is 26, is inserted after the last character in the file to mark the end of file. There is no such special character present in the binary mode files to mark the end of file.
    • In text file, the text and characters are stored one character per byte. For example, the integer value 1245 will occupy 2 bytes in memory but it will occupy 5 bytes in text file. In binary file, the integer value 1245 will occupy 2 bytes in memory as well as in file.

    The data format is usually line-oriented in text file. Here, each line is a separate command.
    Binary file always needs a matching software to read or write it.(MP3 player Image Viewer)

    Using files in C
    There are four steps in using files

    • Declare a file pointer variable
    • Open a file using fopen() function
    • Process the file using suitable functions
    • Close the file using fclose() function

    Declare a file pointer variable

    To access any file, we need to declare a pointer to FILE structure and then associate it with the particular file. This pointer is referred to as file pointer.

    Syntax for declaring file pointer

                                                                                  FILE * fp;

    A pointer to FILE structure contains information, such as
    size, current file  position, type of file etc., to perform operation on
    the file.Opening a file function

    Open a file using fopen() function

    The fopen() function takes two arguments, the name of the
    file and the mode in which the file is to be opened. Mode specify the purpose
    of opening the file i.e, whether for reading or writing.

    Syntax for opening the file in C

            fp =
    fopen(char *filename,char *mode);

    When fopen() function opens a file in memory, it returns a
    pointer to this particular file.If fopen() function can’t open the file then
    it will return NULL.

    Example for opening a text file for reading in C

           void main()

           {

                  FILE *fp;

                  fp = fopen(«file1.txt»,»r»);      //statement 1

                  if(fp == NULL)

                  {

                         printf(«nCan’t open
    file or file doesn’t exist.»);

                         exit(0);

                  }

    In the above example, statement 1 will open an existing text file «file1.txt» in
    read mode and return a pointer to file. If file will not open, an appropriate
    message will be displayed.

    File opening modes

    Mode

    Meaning

    r

    Open a text file for reading

    w

    Create a text file for writing

    a

    Append to a text file

    rb

    Open a binary file for reading

    wb

    Open a binary file for writing

    ab

    Append to a binary file

    r+

    Open a text file for read/write

    w+

    Create  a text file for
    read/write

    a+

    Append or create a text file for read/write

    r+b

    Open a binary file for read/write

    w+b

    Create a binary file for read/write

    a+b

    Append a binary file for read/write

    Note: The complete path of the file must be specified, if
    the file is not in the current directory. Most of the functions prototype for
    file handling is mentioned in stdio.h.

    Close the file using fclose() function

    When the
    reading or writing of a file is finished, the file should be closed properly
    using fclose() function. The fclose() function does the following tasks:

    Flushes any
    unwritten data from memory.

    Discards any
    unread buffered input.

    Frees any
    automatically allocated buffer

    Finally,
    close the file.

    Syntax for
    closing the file in C

                  int fclose( FILE* );

    Example for
    closing the file in C

           void main()

           {

                  FILE *fp;

                  fp =
    fopen(«file1.txt»,»r»);

                  if(fp == NULL)

                  {

                         printf(«nCan’t open
    file or file doesn’t exist.»);

                         exit(0);

                  }

                        — — — — — — — — — —

                        — — — — — — — — — —

                  fclose(fp);

           }

    Note: A
    stream’s buffer can be flushed without closing it by using the fflush() library function.The flushall() command flush all open
    streams.pointer

    As long as your program is running, if you keep opening files without
    closing them, the most likely result is that you will run out of file
    descriptors/handles available for your process, and attempting to open
    more files will fail eventually. On Windows, this can also prevent
    other processes from opening or deleting the files you have open, since
    by default, files are opened in an exclusive sharing mode that prevents
    other processes from opening them.

    Once your program exits, the operating system will clean up after
    you. It will close any files you left open when it terminates your
    process, and perform any other cleanup that is necessary (e.g. if a file
    was marked delete-on-close, it will delete the file then; note that
    that sort of thing is platform-specific).

    However, another issue to be careful of is buffered data. Most file streams buffer data in memory before writing it out to disk. If you’re using FILE* streams from the stdio library, then there are two possibilities:

    Your program exited normally, either by calling the exit(3) function, or by returning from main (which implicitly calls exit(3)).
    Your program exited abnormally; this can be via calling abort(3) or _Exit(3), dying from a signal/exception, etc.

    If your program exited normally, the C runtime will take care of
    flushing any buffered streams that were open. So, if you had buffered
    data written to a FILE* that wasn’t flushed, it will be flushed on normal exit. 

    Conversely, if your program exited abnormally, any buffered data will not
    be flushed. The OS no idea there’s some random data lying somewhere in memory that the
    program intended to write to disk but did not. So be careful about
    that.

    Working with Text files

    The
    following functions provides facility for reading and writing files

    Reading

    Writing

    fgetc()

    fputc()

    fgets()

    fputs()

    fscanf()

    fprintf()

    fread()

    fwrite()

    Character Input and Output

    Characters
    or a line (sequence of characters terminated by a newline) can be written or
    read from a file using following functions.

    putc() / fputc() function

    The library
    function putc() writes a single character to a specified stream.Its prototype is

    int putc(int
    ch,FILE *fp);

    Eg:

    char c=’x’;

    FILE
    *fp=fopen(“abc.txt”,”w”);

    putc(c,fp);
    // fputc(c,fp) // char x is written to file abc.txt.

    fputs() function

    To write a
    line of characters to a stream, the library function fputs() is used.Its
    prototype is

    char
    fputs(char *str,FILE *fp);

    Eg:

    char
    str[]=”cek”;

    FILE
    *fp=fopen(“abc.txt”,”w”);

    fputs(str,fp);
    // string cek is written into file abc.txt

    getc() / fgetc() function

    The function
    getc() and fgetc() are identical and can be used interchangeably. They input a
    single character from a specified stream.Its prototype is

    int
    getc(FILE *fp);

    Eg:

    FILE
    *fp=fopen(“abc.txt”,”r”);

    int c;

    c=fgetc(fp);
    // reads a character

    fgets() function

    fgets() is a
    line oriented function for reading from a file.Its prototype is

    char
    *fgets(char *str,int n, FILE *fp);

    Eg:

    FILE
    *fp=fopen(“abc.txt”,”r”);

    char
    line[60];

    char *c;

    c=fgets(line,60,fp);

    The other
    two file handling functions to be covered are fprintf() and fscanf().These
    functions operate exactly like printf() and scanf() except that they work with
    files.

    Their prototypes are

    int fprintf(FILE
    *fp, const char *control-string,…);

    int fscanf(FILE
    *fp, const char *control-string,…);

    Eg:

    FILE *fp=fopen(«abc.txt»,»w»);
    fprintf(fp,”%s”,”cek”);
    FILE *fp=fopen(«abc.txt»,»r»);int n;
    fscanf(fp,»%d»,&n);

    putw() and getw() function
    The putw() function is used to write integers to the file.
    Syntax of putw() function

    putw(int number, FILE *fp);

    The putw() function takes two arguments, first is an integer value to be written to the file and second is the file pointer where the number will be written.

     eg:putw(n,fp)
    The getw() function is used to read integer value form the file.
    Syntax of getw() function
      int getw(FILE *fp);
    Eg:
    while((num = getw(fp))!=EOF)

    printf(«n%d»,num);

    Binary Files and Direct File I/O

    The
    operations performed on binary files are similar to text files since both types
    of files can essentially be considered as stream of bytes. In fact the same
    functions are used to access files in C. When a file is opened, it must be
    designated as text or binary and usually this is the only indication of the
    type of file being processed.

    Direct I/O is used only with binary-mode files. With direct output,
    blocks of data are written from memory to disk and in direct input block of
    data are read  from disk to memory.For
    example, a single direct-output function can write an entire array to disk and
    a single direct input function call can read the entire array from disk back to
    memory.

    The C file
    system includes two important functions for direct I/O: fread() and fwrite().Their
    prototypes are

    size_t
    fread(void *buffer, size_t size,size_t num,FILE *fp)

    size_t
    fwrite(void *buffer, size_t size,size_t num,FILE *fp)

    The fread() function reads from the file associated with fp, num
    number of objects, each object size in bytes, into buffer pointed to by buffer.fwrite() function is the opposite
    of fread().It writes to files associated with fp,num number of objects, each object size in bytes, from the
    buffer pointed to by buffer.

    Sample Programs

    Read and display a file character by
    character using getc/fgetc function

    #include
    <stdio.h>

    #include
    <stdlib.h>

    int main()

    {

    FILE *fp;

    int ch;

    fp=fopen(«a.txt»,»r»);

    if(fp==NULL)

      {

      printf(«Error opening file..»);

      exit(1);

       }

    while((ch=getc(fp))!=EOF) // can use ch=fgetc(fp) also

    {

    putchar(ch);

     }

    fclose(fp);

    }
    vowels consonants digits and special characters in a file ( university question)
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
    FILE *fp;
    int ch,vowels=0,consonants=0,digits=0,specc=0,c=0;
    fp=fopen(«a.txt»,»r»);
    if(fp==NULL)
      {
      printf(«Error opening file..»);
      exit(1);
       }
    while((ch=fgetc(fp))!=EOF)
    {
       if(ch==’a’ || ch==’e’ || ch==’i’ ||
               ch==’o’ || ch==’u’ || ch==’A’ ||
               ch==’E’ || ch==’I’ || ch==’O’ ||
               ch==’U’)
            {
                ++vowels;
            }
            else if((ch>=’a’&& ch<=’z’) || (ch>=’A’&& ch<=’Z’))
            {
                ++consonants;
            }
            else if(ch>=’0′ && ch<=’9′)
            {
                ++digits;
            }
            else if (ch ==’ ‘ || ch ==’n’)
            {
                ++specc;
            }
    c++;
     }
        printf(«Vowels: %d»,vowels);
        printf(«nConsonants: %d»,consonants);
        printf(«nDigits: %d»,digits);
        printf(«nSpecial characters: %dn», c-specc-vowels-consonants-digits);
    fclose(fp);
    }  
    Reading line by line from a file using
    fgets

    #include
    <stdio.h>

    #include
    <stdlib.h>

    int main()

    {

    FILE *fp;

    char * ch;

    char
    line[80];

    fp=fopen(«a.txt»,»r»);

    if(fp==NULL)

      {

      printf(«Error opening file..»);

      exit(1);

       }

    while((fgets(line,80,fp)!=NULL)

    {

     printf(«%s»,line);

    }

    fclose(fp);

    }
    Reading word by word using fscanf
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
    FILE *fp;
    char t[100];
    fp=fopen(«a.txt»,»r»);
    if(fp==NULL)
      {
      printf(«Error opening source file..»);
      exit(1);
       }
    while(fscanf(fp,»%s»,t)==1)
    {
    printf(«%sn»,t);
    }
    fclose(fp);
    }

    Write data to the file( char by char using putc/fputc function)
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
    FILE *fp;
    int ch;
    fp=fopen(«a.txt»,»w»);
    if(fp==NULL)
      {
      printf(«Error opening file..»);
      exit(1);
       }
    do{
       ch=getchar();
       if (ch==’$’) break;
       putc(ch,fp); //fputc(ch,fp);
      }
    while(1);
    fclose(fp);
    }
    Write data to the file( as strings using fputs function)
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int main()
    {
    FILE *fp;
    char t[80];
    fp=fopen(«a.txt»,»w»);
    if(fp==NULL)
      {
      printf(«Error opening file..»);
      exit(1);
       }
    printf(«Enter strings…type end to stopn»);
    do{
       fgets(t,80,stdin);
       printf(«%sn»,t);
       if(strcmp(t,»endn»)==0 ) break;
       fputs(t,fp);
      }
    while(1);
    fclose(fp);
    }
    C Program to delete a specific line from a text file
    #include <stdio.h> 

    int main() 

    { FILE *fp1, *fp2; //consider 40 character string to store filename 

    char filename[40]; 

    char c; int del_line, temp = 1; 

    //asks user for file name

     printf(«Enter file name: «); 

    //receives file name from user and stores in ‘filename’ 

    scanf(«%s», filename); 

    //open file in read mode 

    fp1 = fopen(filename, «r»); 

    c = getc(fp1); //until the last character of file is obtained 

    while (c != EOF) 

    { printf(«%c», c); //print current character and read next character

     c = getc(fp1); 

    //rewind 

    rewind(fp1);

     printf(» n Enter line number of the line to be deleted:»); 

    //accept number from user. 

    scanf(«%d», &del_line);

    //open new file in write mode 

    fp2 = fopen(«copy.c», «w»); 

    c = getc(fp1); 

    while (c != EOF) 

    { c = getc(fp1); 

    if (c == ‘n’) temp++; //except the line to be deleted

    if (temp != del_line) { //copy all lines in file copy.c putc(c, fp2); } } //close both the files. fclose(fp1); 

    fclose(fp2); 

    //remove original file 

    remove(filename); 

    //rename the file copy.c to original name 

    rename(«copy.c», filename); 

    printf(«n The contents of file after being modified are as follows:n»);

     fp1 = fopen(filename, «r»);

     c = getc(fp1); 

    while (c != EOF) 

    { printf(«%c», c); 

       c = getc(fp1);

     } 

    fclose(fp1); return 0; 

    }
    Write data to the file( as strings using fprintf)
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
    FILE *fp;
    fp=fopen(«a.txt»,»w»);
    if (fp==NULL)
      {
        printf(«error opening file..n»);
        exit(1);
       }
    else
      {
       fprintf(fp,»%s»,»Welcomen»);
       fprintf(fp,»%s»,»to file handling in Cn»);
       }
    fclose(fp);
    }

    Counting number of lines, characters and
    words in a file

    #include
    <stdio.h>

    #include
    <stdlib.h>

    int main()

    {

    FILE *fp;

    int ch;

    int
    nl=0,nc=0,nw=0;

    fp=fopen(«a.txt»,»r»);

    if(fp==NULL)

      {

      printf(«Error opening file..»);

      exit(1);

       }

    ch=getc(fp);

    while(ch!=EOF)

    {

    if
    (ch==’n’) nl++;

    if(ch==’ ‘)
    nw++;

    nc++;

    ch=getc(fp);

    }

    fclose(fp);

    printf(«Number
    of lines=%d, Number of characters = %d,Number of words=%dn»,nl,nc,nw+nl);

    }

    Cheking whether two files are identical or
    different

    #include
    <stdio.h>

    #include
    <stdlib.h>

    int main()

    {

    FILE
    *fp1,*fp2;

    int ca,cb;

    char
    fname1[50],fname2[50];

    printf(«Enter
    the first file name…n»);

    scanf(«%s»,fname1);

    printf(«Enter
    the second file name…n»);

    scanf(«%s»,fname2);

    fp1=fopen(fname1,»r»);

    fp2=fopen(fname2,»r»);

    if(fp1==NULL)

      {

      printf(«Error opening file1..»);

      exit(1);

       }

    else
    if(fp2==NULL)

       {

        printf(«Error opening file2..»);

        exit(1);

       }

    else

    {

    ca=getc(fp1);

    cb=getc(fp2);

    while(ca!=EOF
    && cb!=EOF && ca==cb)

    {

    ca=getc(fp1);

    cb=getc(fp2);

    }

    fclose(fp1);

    fclose(fp2);

    if(ca==cb)

    printf(«Files
    are identicaln»);

    else if
    (ca!=cb)

    printf(«Files
    are different n»);

    }

    }

    Copy one file to another character by
    character using getc and putc function( you can also use fgetc and fputc)

    #include
    <stdio.h>

    #include
    <stdlib.h>

    int main()

    {

    FILE
    *fp1,*fp2;

    int ch;

    char
    fname1[50],fname2[50];

    printf(«Enter
    the source file name…n»);

    scanf(«%s»,fname1);

    printf(«Enter
    the destination file name…n»);

    scanf(«%s»,fname2);

    fp1=fopen(fname1,»r»);

    fp2=fopen(fname2,»w»);

    if(fp1==NULL)

      {

      printf(«Error opening source
    file..»);

      exit(1);

       }

    else
    if(fp2==NULL)

       {

        printf(«Error opening destination
    file..»);

        exit(1);

       }

    else

    {

    while((ch=fgetc(fp1))!=EOF)
       {
         fputc(ch,fp2);
       }

    }

    fclose(fp1);

    fclose(fp2);

    printf(«Files
    succesfully copiedn»);

    }

    }
    Copy one file to another after replacing lower case letters with corresponding uppercase letters.(university question)
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
    FILE *fp1,*fp2;
    int ch;
    char fname1[50],fname2[50];
    printf(«Enter the source file name…n»);
    scanf(«%s»,fname1);
    printf(«Enter the destination file name…n»);
    scanf(«%s»,fname2);
    fp1=fopen(fname1,»r»);
    fp2=fopen(fname2,»w»);
    if(fp1==NULL)
      {
      printf(«Error opening source file..»);
      exit(1);
       }
    else if(fp2==NULL)
       {
        printf(«Error opening destination file..»);
        exit(1);
       }
    else
    {
        while((ch=fgetc(fp1))!=EOF)
       {
          if(islower(ch)) ch=toupper(ch);

         fputc(ch,fp2);
        }
    fclose(fp1);
    fclose(fp2);
    printf(«Files succesfully copiedn»);
    }
    }

    Write a C program to replace vowels in a text file with character ‘x’.(university question)

    #include <stdio.h>

    #include <stdlib.h>

    int isvowel(char ch)

    {

         ch=tolower(ch);

       switch(ch)

       {

           case ‘a’:

           case ‘e’:

           case ‘i’:

           case ‘o’:

           case ‘u’:

                    return 1;

       }

        return 0;

    }

    int main()

    {

    FILE *fp1,*fp2;

    int ch;

    char fname1[50],fname2[50];

    fp1=fopen(«vow.dat»,»r»);

    fp2=fopen(«x.dat»,»w»);

    if(fp1==NULL)

      {

      printf(«Error opening source file..»);

      exit(1);

       }

    else if(fp2==NULL)

       {

        printf(«Error opening destination file..»);

        exit(1);

       }

    else

    {

        while((ch=fgetc(fp1))!=EOF)

       {

          if(isvowel(ch)) ch=’x’;

         fputc(ch,fp2);

        }

    fclose(fp1);

    fclose(fp2);

    //remove the original file

    remove(«vow.dat»); 

    //rename the file temp file x.dat to original name 

    rename(«x.dat», «vow.dat»);

    printf(«Files successfully copiedn»);

    }

    }

    Copy one file to another line by line using
    fgets and fputs function

    #include
    <stdio.h>

    #include
    <stdlib.h>

    int main()

    {

    FILE
    *fp1,*fp2;

    int ch;

    char
    fname1[50],fname2[50],t[80];

    printf(«Enter
    the source file name…n»);

    scanf(«%s»,fname1);

    printf(«Enter
    the destination file name…n»);

    scanf(«%s»,fname2);

    fp1=fopen(fname1,»r»);

    fp2=fopen(fname2,»w»);

    if(fp1==NULL)

      {

      printf(«Error opening source
    file..»);

      exit(1);

       }

    else
    if(fp2==NULL)

       {

        printf(«Error opening destination
    file..»);

        exit(1);

       }

    else

    {

    while((fgets(t,sizeof(t),fp1)!=NULL))

    {

    fputs(t,fp2);

    }

    fclose(fp1);

    fclose(fp2);

    printf(«Files
    succesfully copiedn»);

    }

    }
    Merging the contents of two files into a third file(university question)
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
    FILE *fp1,*fp2,*fp3;
    char t[100];
    fp1=fopen(«first.txt»,»r»);
    fp2=fopen(«second.txt»,»r»);
    fp3=fopen(«third.txt»,»w»);
    if(fp1==NULL||fp2==NULL)
      {
      printf(«Error opening source file..»);
      exit(1);
       }
    else if(fp3==NULL)
       {
        printf(«Error opening destination file..»);
        exit(1);
       }
    else
    {
    while((fgets(t,sizeof(t),fp1)!=NULL))
    {
    fputs(t,fp3);
    }
    while((fgets(t,sizeof(t),fp2)!=NULL))
    {
    fputs(t,fp3);
    }
    fclose(fp1);
    fclose(fp2);
    fclose(fp3);
    printf(«Files succesfully mergedn»);
    }
    }

    Reading numbers from a file and separating
    even and odd numbers 
    into two different files

    #include
    <stdio.h>

    #include
    <stdlib.h>

    int main()

    {

    FILE
    *fp,*fpe,*fpo;

    int n;

    fp=fopen(«num.dat»,»r»);

    fpe=fopen(«enum.dat»,»w»);

    fpo=fopen(«onum.dat»,»w»);

    if
    (fp==NULL||fpe==NULL||fpo==NULL)

      {

        printf(«error opening file..n»);

        exit(1);

       }

    else

      {

    while(fscanf(fp,»%d»,&n)==1)

       {

        if (
    n%2==0)

         fprintf(fpe,»%dn»,n);

      else

        fprintf(fpo,»%dn»,n);

       }

    fclose(fp);

    fclose(fpe);

    fclose(fpo);

    }

    }
    Note: this program can also be written using putw() getw() function

    Write Palindrome words from a file to a new file

     #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int palindrome(char str[50])
    {
      int i,j;
       for(i=0,j=strlen(str)-1;i<j;i++,j—)
        if(str[i]!=str[j]) return 0;
      return 1;
    }
    int main()
    {  
         FILE *fp1,*fp2;
     char word[50];
      fp1=fopen(«words.txt»,»r»);
      fp2=fopen(«palwords.txt»,»w»);
       while((fscanf(fp1,»%s»,word))!=EOF)
       {
         if(palindrome(word)) fprintf(fp2,»%sn»,word);
       }

        fclose(fp1); 
       fclose(fp2);           

      }

    Reading
    an array and writing to a file using fwrite and reading the file 
    using fread

    #include <stdio.h>

    #include <stdlib.h>

    #define SIZE 10

    int main()

    {

    int i,a[SIZE],b[SIZE];

    FILE *fp;

    printf(«Enter 10 elements in
    array a…n»);

    for(i=0;i<10;i++)

     
    scanf(«%d»,&a[i]);

    fp=fopen(«num.dat»,»w»);

    if(fp==NULL)

     {

     printf(«error opening file..n»);

     exit(1);

     }

    fwrite(a,sizeof(int),SIZE,fp);

    fclose(fp);

    /*opening the file and reading to
    array b*/

    fp=fopen(«num.dat»,»r»);

    if(fp==NULL)

     {

     printf(«error opening file..n»);

     exit(1);

     }

    fread(b,sizeof(int),SIZE,fp);

    printf(«array b is…n»);

    for(i=0;i<10;i++)

     printf(«%dn»,b[i]);

    fclose(fp);

    } 
    Program for writing struct
    to file using fwrite

    #include
    <stdio.h>
    #include
    <stdlib.h>
    #include
    <string.h>
    struct person

    {

        int
    id;

        char
    fname[20];

        char
    lname[20];

    };

    int main ()

    {

        FILE
    *outfile;

        //
    open file for writing

        outfile
    = fopen («person.dat», «w»);

        if
    (outfile == NULL)

        {

            fprintf(stderr,
    «nError opend filen»);

            exit
    (1);

        }

        struct
    person input1 = {1, «rohit», «sharma»};

        struct
    person input2 = {2, «mahendra», «dhoni»};

           //
    write struct to file

        fwrite
    (&input1, sizeof(struct person), 1, outfile);

        fwrite
    (&input2, sizeof(struct person), 1, outfile);

         if(fwrite != 0)

            printf(«contents
    to file written successfully !n»);

        else

            printf(«error
    writing file !n»);

        return 0;

    }
    Write a C program to create a file and store information about a person, in terms of his name, age and salary.(university question)
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    struct person
    {
        char name[50];
        int  age;
        int  salary;
    };
    int main ()
    {
        FILE *outfile;
        // open file for writing
        outfile = fopen («person.dat», «w»);
        if (outfile == NULL)
        {
            fprintf(stderr, «nError opend filen»);
            exit (1);
        }
        struct person input1 = {«rohit»,45,20000};
        struct person input2 = {«mahendra»,25,15000};
           // write struct to file
        fwrite (&input1, sizeof(struct person), 1, outfile);
        fwrite (&input2, sizeof(struct person), 1, outfile);
         if(fwrite != 0)
            printf(«contents to file written successfully !n»);
        else
            printf(«error writing file !n»);
        return 0;

    }

    Program for reading struct using fread

    This program will read the file person.dat file
    in the previous program.

    #include
    <stdio.h>

    #include
    <stdlib.h>

     //
    struct person with 3 fields

    struct person

    {

        int
    id;

        char
    fname[20];

        char
    lname[20];

    };

    int main ()

    {

        FILE
    *infile;

        struct
    person input;

        //
    Open person.dat for reading

        infile
    = fopen («person.dat», «r»);

        if
    (infile == NULL)

        {

            fprintf(stderr,
    «nError opening filen»);

            exit
    (1);

        }

           //
    read file contents till end of file

        while(fread(&input,
    sizeof(struct person), 1, infile))

            printf
    («id = %d name = %s %sn», input.id,

            input.fname,
    input.lname);

        return
    0;

    }

    Random Access To File

    There is no need to read each record sequentially, if we want to access a particular record. C supports these functions for random access file processing.

    fseek()

    ftell()

    rewind()

    fseek()
    This function is used for seeking the pointer position in the file at the specified byte.
    Syntax:

    fseek(FILE
    *fp,long offset,int position)

    Where
    fp-file pointer —- It is the pointer which points to the file.
    offset -displacement —- It is positive or negative.This is the number of
    bytes which are skipped backward (if negative) or forward( if positive) from
    the current position.This is attached with L because this is a long integer.
    Pointer position:
    This sets the pointer position in the file.

    Value     Pointer position

    0               Beginning
    of file.

    1               Current
    position

    2               End
    of file

    Ex:

    1) fseek(
    p,10L,0)
    0 means pointer position is on beginning of the file,from this statement
    pointer position is skipped 10 bytes from the beginning of the file.
    2)fseek( p,5L,1)
    1 means current position of the pointer position.From this statement pointer
    position is skipped 5 bytes forward from the current position.
    3)fseek(p,-5L,1)

    From this statement pointer position is skipped 5 bytes backward from the current
    position.

    ftell()

    This function returns the value of the current pointer position in the file.The value is count from the beginning of the file.

    Syntax: long ftell(FILE *fptr);
    Where fptr is a file pointer.

    rewind()

    This function is used to move the file pointer to the beginning of the given file.

    Syntax:

    void rewind(FILE *fptr);

    Where fptr is a file pointer.


    Example program for fseek():

    Write a program to read last ‘n’ characters of the file using appropriate file
    functions(Here we need fseek() and fgetc()).

    #include<stdio.h>

    #include<conio.h>

    void main()

    {

         FILE *fp;

         char ch;

         clrscr();

         fp=fopen(«file1.c», «r»);

         if(fp==NULL)

            printf(«file
    cannot be opened»);

         else

        {

                printf(«Enter
    value of n  to read last ‘n’ characters»);

                scanf(«%d»,&n);

                fseek(fp,-n,2);

                while((ch=fgetc(fp))!=EOF)

                {

                     printf(«%ct»,ch);

                }

          }

    }

    Programs to try 

    2.Open a text input file and count number of characters, words and lines in it; and store the results

    in an output file.

    3.Copy one file to another.

    4.Merge the content of two files and copy to the other.

    5.Read numbers from a file and separate even and odd numbers into two different files.

    6.Create a structure employee with fields empid,name and salary.Write the structure into a file.

    7.Write an integer array into a file.Read and display the array elements in reverse order.

    8.Read last n characters from a file.

    9.Find the palindrome words from a file and write it into a new file.

    1. Use std::ifstream to Read File Word by Word in C++
    2. Use std::ispunct and std::string::erase Functions to Parse Punctuation Symbols in C++

    Read File Word by Word in C++

    This article will demonstrate multiple methods about how to read a file word by word in C++.

    Use std::ifstream to Read File Word by Word in C++

    The std::ifstream class can be utilized to conduct input operations file-based streams. Namely, the std::ifstream type is used to interface with file buffer and operate on it using the extraction operator. Note that, std::fstream type is also provided in the I/O library that’s compatible with both extraction (>>) and insertion operators (<<).

    At first, we need to create an object of type ifstream by calling one of its constructors; in this case, only filename string is passed to the constructor function. Once the ifstream object is created, one of its methods — is_open should be called to verify that the call was successful and then proceed to read the file contents.

    To read the file word by word, we call the extraction operator on ifstream object. We redirect it to the string variable, which automatically reads in the first word before the first space character is encountered. Since we need to read each word until the end of the file, we insert the extraction statement into a while loop expression. Additionally, we declared a vector of strings to store each word on every iteration and print later with a separate loop block.

    #include <iostream>
    #include <fstream>
    #include <vector>
    
    using std::cout; using std::cerr;
    using std::endl; using std::string;
    using std::ifstream; using std::vector;
    
    int main()
    {
        string filename("input.txt");
        vector<string> words;
        string word;
        
        ifstream input_file(filename);
        if (!input_file.is_open()) {
            cerr << "Could not open the file - '"
                 << filename << "'" << endl;
            return EXIT_FAILURE;
        }
    
        while (input_file >> word) {
            words.push_back(word);
        }
        
        for (const auto &i : words) {
            cout << i << endl;
        }
        input_file.close();
    
        return EXIT_SUCCESS;
    }
    

    Use std::ispunct and std::string::erase Functions to Parse Punctuation Symbols in C++

    The only downside of the previous method is that it stores the punctuation characters close to words in the destination vector. It would be better to parse each word and then store them into a vector container. We are using the ispunct function that takes a single character as int parameter and returns a non-zero integer value if the character is punctuation; otherwise — zero is returned.

    Note that the behavior of ispunct function is undefined if the given argument is not representable as unsigned char; thus, it is recommended to cast the character to the corresponding type. In the following example, we implemented the two simple if conditions to check the first and last characters of each word. If the punctuation is found, we call a built-in string function — erase to remove the found characters.

    #include <iostream>
    #include <fstream>
    #include <vector>
    
    using std::cout; using std::cerr;
    using std::endl; using std::string;
    using std::ifstream; using std::vector;
    
    int main()
    {
        string filename("input.txt");
        vector<string> words;
        string word;
        
        ifstream input_file(filename);
        if (!input_file.is_open()) {
            cerr << "Could not open the file - '"
                 << filename << "'" << endl;
            return EXIT_FAILURE;
        }
    
        while (input_file >> word) {
            if (ispunct(static_cast<unsigned char>(word.back())))
                word.erase(word.end()-1);
            else if (ispunct(static_cast<unsigned char>(word.front())))
                word.erase(word.begin());
            
            words.push_back(word);
        }
        
        for (const auto &i : words) {
            cout << i << endl;
        }
        input_file.close();
    
        return EXIT_SUCCESS;
    }
    

    I found something that at least begins to answer my own question. The following two links have wmv files from Microsoft that demonstrate using a C# class in unmanaged C++.

    This first one uses a COM object and regasm: http://msdn.microsoft.com/en-us/vstudio/bb892741.

    This second one uses the features of C++/CLI to wrap the C# class: http://msdn.microsoft.com/en-us/vstudio/bb892742. I have been able to instantiate a c# class from managed code and retrieve a string as in the video. It has been very helpful but it only answers 2/3rds of my question as I want to instantiate a class with a string perimeter into a c# class. As a proof of concept I altered the code presented in the example for the following method, and achieved this goal. Of course I also added a altered the {public string PickDate(string Name)} method to do something with the name string to prove to myself that it worked.

    wchar_t * DatePickerClient::pick(std::wstring nme)
    {
        IntPtr temp(ref);// system int pointer from a native int
        String ^date;// tracking handle to a string (managed)
        String ^name;// tracking handle to a string (managed)
        name = gcnew String(nme.c_str());
        wchar_t *ret;// pointer to a c++ string
        GCHandle gch;// garbage collector handle
        DatePicker::DatePicker ^obj;// reference the c# object with tracking handle(^)
        gch = static_cast<GCHandle>(temp);// converted from the int pointer 
        obj = static_cast<DatePicker::DatePicker ^>(gch.Target);
        date = obj->PickDate(name);
        ret = new wchar_t[date->Length +1];
        interior_ptr<const wchar_t> p1 = PtrToStringChars(date);// clr pointer that acts like pointer
        pin_ptr<const wchar_t> p2 = p1;// pin the pointer to a location as clr pointers move around in memory but c++ does not know about that.
        wcscpy_s(ret, date->Length +1, p2);
        return ret;
    }
    

    Part of my question was: What is better? From what I have read in many many efforts to research the answer is that COM objects are considered easier to use, and using a wrapper instead allows for greater control. In some cases using a wrapper can (but not always) reduce the size of the thunk, as COM objects automatically have a standard size footprint and wrappers are only as big as they need to be.

    The thunk (as I have used above) refers to the space time and resources used in between C# and C++ in the case of the COM object, and in between C++/CLI and native C++ in the case of coding-using a C++/CLI Wrapper. So another part of my answer should include a warning that crossing the thunk boundary more than absolutely necessary is bad practice, accessing the thunk boundary inside a loop is not recommended, and that it is possible to set up a wrapper incorrectly so that it double thunks (crosses the boundary twice where only one thunk is called for) without the code seeming to be incorrect to a novice like me.

    Two notes about the wmv’s. First: some footage is reused in both, don’t be fooled. At first they seem the same but they do cover different topics. Second, there are some bonus features such as marshalling that are now a part of the CLI that are not covered in the wmv’s.

    Edit:

    Note there is a consequence for your installs, your c++ wrapper will not be found by the CLR. You will have to either confirm that the c++ application installs in any/every directory that uses it, or add the library (which will then need to be strongly named) to the GAC at install time. This also means that with either case in development environments you will likely have to copy the library to each directory where applications call it.

    I am very new to C. I am trying to read the words from a file which contains lots of not alpha characters. My input file looks something like this %tOm12%64ToMmy%^$$6 and I want to read tom first and then put tom in my data structure and then read tommy and put that in my data structure all in lowercase. This is what I have tried until now. All my other code works as I have manually sent the parameters to the methods and there are no errors. This is what I have tried to read the words from the file. A word can be of 100 characters max. Can someone help me understand the logic and possibly this code.I am very lost.Thank You!

    void read(FILE *fp)
    {
      FILE *fp1 = fp;
      char word[100];
      int x;
      int counter = 0;
    
      while ((x = fgetc(fp1)) != EOF)
      {
         if (isalpha(x) == 0)
         {
            insert(&tree,word);
            counter = 0;
         }
         if (isalpha(x) != 0)
         {
            tolower(x);
            word[counter] = x;
            counter++;
         }
      }
      rewind(fp1);
      fclose(fp1);
    }
    

    2 Answers

    char *getWord(FILE *fp){
        char word[100];
        int ch, i=0;
    
        while(EOF!=(ch=fgetc(fp)) && !isalpha(ch))
            ;//skip
        if(ch == EOF)
            return NULL;
        do{
            word[i++] = tolower(ch);
        }while(EOF!=(ch=fgetc(fp)) && isalpha(ch));
    
        word[i]='';
        return strdup(word);
    }
    void read(FILE *fp){
        char *word;
        while(word=getWord(fp)){
            insert(&tree, word);
        }
        //rewind(fp1);
        fclose(fp);
    }
    

    This is a simplification of @BLUEPIXY ‘s answer. It also checks the array boundaries for word[]

    char *getword(FILE *fp)
    {
        char word[100];
        int ch; 
        size_t idx ;
    
        for (idx=0; idx < sizeof word -1; ) {
            ch = fgetc(fp);
            if (ch == EOF) break;
            if (!isalpha(ch)) {
               if (!idx) continue; // Nothing read yet; skip this character
               else break; // we are beyond the current word
               }
            word[idx++] = tolower(ch);
            }
        if (!idx) return NULL; // No characters were successfully read
        word[idx] = '';
        return strdup(word);
    }
    

    First of all sorry for my bad english… I will try to make not so many mistakes:D

    Ok i need to write a programs that reads some text from a file and then it outputs the statistics of the words. So i have already completed that the programs says how many charecters there are in a text. Now i would like you to help me with something.

    I want to do a function that reads the text from file and than output it like this:

    read text : Today is very warm.

    text output when i run programe:
    Today
    is
    very
    warm

    So i think i need to read this text from some file than put it in array and then output it with for sentence.

    ifstream entrance;
    char word;

    entrance.open(«lala.txt»);
    while (!entrance.eof())
    {
    ………
    ………

    }
    entrance.close();

    for(i=0; i…..)
    cout<<word[i]<<endl;

    But i dont know how to do this…

    So can you pls help me.

    Thank you all!

    somehow like this

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    char string[256];
    //read file into string
    
    int pos=0;
    char* word=string;
    while(pos<256 && string[pos]!=0) {
     if(string[pos]==' ') {
      string[pos]=0;
      std::cout<<word<<std::endl;
      word=string+pos;
     }
     pos+=sizeof(char);
    }
    std::cout<<word<<std::endl;

    Last edited on

    i do this inside or where?

    ifstream entrance;

    entrance.open(«lala.txt»);
    while (!entrance.eof())
    {
    ………
    ………

    }
    entrance.close();

    And how do i tell that the text that is inside a file is stored in string?

    The good old c++ way!

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    #include <string>
    #include <vector>
    #include <fstream>
    #include <iostream>
    
    int main()
    {
      std::vector <std::string> words; // Vector to hold our words we read in.
      std::string str; // Temp string to
      std::cout << "Read from a file!" << std::endl;
    
      std::ifstream fin("thisfile.txt"); // Open it up!
      while (fin >> str) // Will read up to eof() and stop at every
      {                  // whitespace it hits. (like spaces!)
        words.push_back(str);
      }
      fin.close(); // Close that file!
    
      for (int i = 0; i < words.size(); ++i)
        std::cout << words.at(i) << std::endl; // Print so I can see this all worked!
    
      return 0;
    }
    

    Can i change this line how std::vector <std::string> words;?

    Couse we havent done anything with vectors, so is it any other posibility to write this ?

    You could use an regular array with strings… I suppose.

    thisfile wrote:
    THIS IS A TEST HERE
    HOLD ON
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    #include <string>
    #include <fstream>
    #include <iostream>
    
    int main()
    {
      const int SIZE = 10;
      std::string words[SIZE]; // C array? to hold our words we read in.
      std::string str; // Temp string to
      std::cout << "Read from a file!" << std::endl;
    
      std::ifstream fin("thisfile.txt");
      for (int i = 0; (fin >> str) && (i < SIZE); ++i) // Will read up to eof() and stop at every
      {                                                // whitespace it hits. (like spaces!)
        std::cout << "This string is: " << str << std::endl;
        words[i] = str;
      } // We now also need to stop before we hit the no define array space.
      fin.close();
    
      std::cout << std::endl;
      for (int i = 0; i < SIZE; ++i)
        std::cout << words[i] << std::endl;
    
      return 0;
    }
    
    Read from a file!
    This string is: THIS
    This string is: IS
    This string is: A
    This string is: TEST
    This string is: HERE
    This string is: HOLD
    This string is: ON
    
    THIS
    IS
    A
    TEST
    HERE
    HOLD
    ON
    

    yea this code work like a charm, exept for 1 thing :D

    If i change constant of size, to bigger value… like 500. Than when i run a program the words are written like they should be, but there is a big blank spot… And i need to scrol a long way down to get to «press any key to continue». So the programe doest stops when there are no more words to output but it still outputs…. :D

    Use a std::vector instead of an array. It doesn’t make sense to use an array when you don’t know how many elements you’re going to read in.

    If you don’t know the size of the data you read in use a vector. Thats all I can say. My array solution expects small input.

    Ok so vector is just like array, but you dont need to know the size of data?

    Ok so let me sum up that code with vector. So it reads file and stores data in vector string.

    that ifstream fin(lala.txt) is just like entrance.open(«lala.txt»)?

    What exactly does this mean fin >>str ?

    And what in above code has the same meaning as while (!entrance.eof())?

    So i would like to thanks in advance for all your help… I will try to work something with this code, and if i wont know how to do additional stuff i will ask you guys again :D

    Again thank you for your time and help :P

    that ifstream fin(lala.txt) is just like entrance.open(«lala.txt»)?

    Yes. If you pass a string as argument to the constructor it will open the file for you. You can also let it go out of scope and the destructor will close it for you.

    What exactly does this mean fin >>str ?

    It’s a call to the extraction operator. Same as std::cin >> foo; only you’re getting input from a file stream rather than directly from the user.

    And what in above code has the same meaning as while (!entrance.eof())?

    When used as a boolean value, the expression fin >> str will evaluate to false if the stream goes into fail(), bad() or eof() states.

    Yes. fin is the name of the ifstream variable just like entrance. There is a constructor overload that opens a file immediately. So you can do these:

    1
    2
    3
    4
    std::ifstream entrance("lala.txt"); // SAME AS
    
    std::ifstream entrance;
    entrance.open("lala.txt");

    fin >> str is just like cin >> from iostream.
    The difference here is that fin >> str will read up to a whitespace and stop and in a loop that reads every word in. The reason it works like !entrance.eof() is because entrance.eof() checks to see if the badbit or eof flag is set (its part of streams and is hard to explain here, you’ll learn it later) and if it is, it returns true, otherwise false. Now fin >> has the same check. Once it reads the eof or a badbit flag is on it stops reading.

    The code you have would be the same as mine if you did this as well:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    while (!entrance.eof())
    {
       entrance >> str; // This reads every character up to the first whitespace (tab, space, newline)
       // and inside this loop it will go until the eof() check is true.
    }
    
    while (entrance >> str)
    {
       // Same thing as above, now just waits for entrance >> to read the eof character or get its badbit flag set. Reads every word, ignores whitespace.
    }

    filipe wrote:
    When used as a boolean value, the expression fin >> str will evaluate to false if the stream goes into fail(), bad() or eof() states.
    wolfgang wrote:
    The difference here is that fin >> str will read up to a whitespace and stop and in a loop that reads every word in. The reason it works like !entrance.eof() is because entrance.eof() checks to see if the badbit or eof flag is set

    I though so too, until a week ago or so, when this post surfaced: http://www.cplusplus.com/forum/general/34292/

    It appears that the results from

    operator!

    and

    operator void*

    depend only on the value of the failbit and badbit, but not on the value of eof. The expression fin >> str is therefore not strictly stronger condition compared to the expression !entrance.eof(). Now I see, that the idiom while (fin >> str) { ... } actually works not because the condition fails immediately when the end of the stream is reached (; if that was the case the last word would escape from the body of the loop), but because the condition fails when the stream was exhausted and

    fin

    has no more characters to pass to

    str

    , which results in a

    failbit

    .

    Thinking further in this direction, using the while (!fin.eof()) { fin >> str; ... } approach may be generally incorrect. It may work for extracting strings, but it could be incorrect for say,

    char

    -s. According to some sources (see **), the

    eof

    bit is set when you try to read something past the end of the file, not when you read the last character before the end of the file. So, if the previous extraction reached the end of the file, without reading past it, the !fin.eof() condition will still evaluate to

    true

    , but the following extraction in the next loop iteration will be unsuccessful, because there is nothing left to read, and there will be erroneous extra processing of non-extent input. I’m not sure on this. Any confirmation?

    ** Random picks:
    http://cpp.comsci.us/etymology/include/iostream/eof.html
    http://stackoverflow.com/questions/292740/c-reading-from-a-file-blocks-any-further-writing-why

    Ok i have worked something with the code, but i took that one with arreys and not that one with vectors. Now i have problem, because i have code which tells how many times is some word repeating in the text. And if i have the size of an array 10 and only 7 words in file, it prints 3 empty spaces so he reaches the size 10. I also dunno how do sort the words by size using vectors(i did this by using arrays). So can someone pls rewrite my code from array to vectors but in very simple way so i will understand it pls :D

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    void frequency(string words[WW])
    {
      
       
      string str; // Temp string to
      int counter7 = 0;
      
    
      ifstream fin("lalala.txt");
      for (int i = 0; (fin >> str) && (i < WW); ++i) 
      {                                               
        
        words[i] = str;
      } 
      fin.close();
    
      cout <<endl;
      for (int i = 0; i < WW; ++i)
      {
          counter7=0;
          for (int j = 0; j < WW; j++)
          {
       if (words[j] == words[i]) 
       counter7++;
    
          }
          cout<<words[i]<<":"<<counter7<<endl;
          
       }
       
    
       
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    void size(string words[WW])
    {
      
       
      string str; // Temp string to
      
    
      ifstream fin("lalala.txt");
      for (int i = 0; (fin >> str) && (i < WW); ++i) 
      {                                                
        
        words[i] = str;
      } 
      fin.close();
    
      cout <<endl;
      for (int i = 0; i < WW; ++i)
      {
          for (int j = 0; j < WW; j++)
          {
       if (words[j].length() < words[i].length()) 
                {
                     string a = words[i]; 
                     words[i] = words[j];
                     words[j] = a;
                     
                }
                
       }
       }
       for (int i = 0; i < WW; ++i)
       cout << words[i] <<endl;
       
    }

    Ok i think i rewrite those 2 codes with vectors…. But i have some problem in second code, so can you take a look pls

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    #include <string>
    #include <vector>
    #include <fstream>
    #include <iostream>
    
    int main()
    {
       
      std::vector <std::string> words; // Vector to hold our words we read in.
      std::string str; // Temp string to
      std::cout << "Read from a file!" << std::endl;
      
    
      std::ifstream fin("lala.txt"); // Open it up!
      while (fin >> str) // Will read up to eof() and stop at every
      {                  // whitespace it hits. (like spaces!)
        words.push_back(str);
      }
      fin.close(); // Close that file!
    
      
      for (int i = 0; i < words.size(); ++i)
      {
          for (int j = 0; j < words.size(); j++)
          {
           if (words[j].length() < words[i].length()) 
                {
                     string a = words[i]; 
                     words[i] = words[j];
                     words[j] = a;
                     
                }
                
       }
       }
       for (int i = 0; i < words.size(); ++i)
       cout << words[i] <<endl;
       
       system("pause");
      return 0;
    }

    i have this errors

    string undeclared
    expected `;’ before «a»
    `a’ undeclared (first use this function)
    `cout’ undeclared (first use this function)
    `endl’ undeclared (first use this function)

    You didn’t specify the namespace. You need to specify it like this:

    std::string a = words[i]; in line 28

    std::cout << words[i] << std::endl; in line 37.

    Or instead of typing

    std::

    all over the place, you can use (the using directive):
    using namespace std;

    Insert it after the include directives and it will apply to all of the following function definitions. Like this:

    1
    2
    3
    4
    5
    6
    7
    8
    #include <string>
    #include <vector>
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    int main()

    Insert it at the beginning of a function (like

    main()

    in this case) and it will apply to the body of the function. Like this:

    1
    2
    3
    4
    int main()
    {
       
        using namespace std;

    Then you will not need to prepend

    std::

    anymore.

    Regards

    PS: how can I escape the array indexes, so that they are not treated as a tag?

    Last edited on

    Topic archived. No new replies allowed.

    1. 06-10-2003


      #1

      Bumblebee11 is offline


      Registered User


      Reading in a file word by word

      I am trying to write a program that reads a file name from the
      command line, reads the contents of that file, and output a list of words, one word per line, to a second file, whose name is also on the command line.

      For this program a word is a sequence of alphabetic characters. Any character which is not alphabetic is a separator character.

      I know how to open files and create files but I am not sure what to do so that I can read in just one word at a time. I also want to know of any tips on how to write to the new file. Thank you in advance for any help!

      Example

      input file:
      Hello%$this is just a test!

      output file:
      Hello
      this
      is
      just
      a
      test


    2. 06-10-2003


      #2

      quzah is offline


      ATH0

      quzah's Avatar


      Just continue in whatever book showed you how to open files a page or two, and they’ll show you how to read.

      Basicly there are may ways to do it.
      fgets would work.
      fgetc would also work.
      fscanf would also work…

      Basicly, there are a whole lot of f-ing functions that would do the job.

      Quzah.

      Hope is the first step on the road to disappointment.


    3. 06-10-2003


      #3

      Bumblebee11 is offline


      Registered User


      Open files

      Cool thank you I got it work… I kept forgetting to point to the right spot. Thank you for your help! The only last thing I need to figure out is how to make a new word after a «non letter».

      Example:

      If you use this code:

      Code:

      FILE *fp = fopen(argv[1],"r");
      
      	char buf[10];
      
      		while( fscanf(fp, "%s", buf) != EOF )
      		{
      			printf("%sn", &buf);
      		}

      On an input file that contains:

      This@#$is just a test!

      Your out put will be
      This@#$is
      just
      a
      test!

      What I need the output to be is:
      This
      is
      just
      a
      test

      Last edited by Bumblebee11; 06-10-2003 at 09:15 PM.


    4. 06-10-2003


      #4

      quzah is offline


      ATH0

      quzah's Avatar


      What you would want to do then, is either modify how your fscanf call works, or, use a loop to run through the string you read in, and check for non-alpha characters.

      To do that, something like this would work.

      Quzah.

      Hope is the first step on the road to disappointment.


    5. 06-10-2003


      #5

      Bumblebee11 is offline


      Registered User


      Got it to work

      I was just able to get my program to work. Thank you for your help!!!


    Понравилась статья? Поделить с друзьями:
  • Recordset в миф excel
  • Reading with word bits
  • Referat yuzi namuna word
  • Reading vocabulary word lists
  • Referat usti namuna word