Sukhpreet Singh
Sukhpreet Singh

Reputation: 37

displaying words from a txt file in c/c++

I have a little problem. I have a text file which contains only English words. I want to display only the words from the file, ignoring spaces. Here is the code:

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
#define max 50
void main()
{
    clrscr();
    char output;
    FILE *p;
    char a[max];
    int i=0;
    p=fopen("thisfile.txt","r");
        while(1)
        {
            char ch=fgetc(p);
            if(ch==EOF)
            {
                break;
            }
            else if(ch==' ')
            {
                cout<<a;
                delete [] a;
                            i=0;
            }
            else
            {
                a[i++]=ch;
            }
        }
    fclose(p);
    getch();
}

Now I am getting some unexpected characters in output. Can you mention where the problem is ?

Upvotes: 1

Views: 1452

Answers (5)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153955

I like to be short and concise:

#include <iostream>
#include <iterator>
#include <fstream>
#include <algorithm>

int main() {
   std::copy(std::istream_iterator<std::string>(std::ifstream("test.txt") >> std::ws),
             std::istream_iterator<std::string>(),
             std::ostream_iterator<std::string>(std::cout));
}

Of course, you might want to print something between the words...

Upvotes: 0

Rontogiannis Aristofanis
Rontogiannis Aristofanis

Reputation: 9063

Why don't you try this:

#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>

using namespace std;

int main() {
   clrscr();
   string s;
   ifstream in("file.txt");

   while(in >> s) {
     cout << s << endl;
   }

   in.close();

   return 0;
}

Upvotes: 0

nurettin
nurettin

Reputation: 11736

Here's one way you can iterate through the words:

#include <fstream>
#include <iostream>
#include <ostream>
#include <iterator>
#include <string>

int main()
{
  std::ifstream file("test.txt");
  std::istream_iterator<std::string> begin(file), end;
  for(; begin!= end; ++ begin)
    std::cout<< *begin<< '\n';
}

Upvotes: 1

md5
md5

Reputation: 23707

Some of your variables aren't initialized. (BTW, fgetc returns an int, it's important to test against EOF) An easier solution in standard C:

#include <stdio.h>

int c;

while ((c = getchar()) != EOF) {
     if (c == ' ')
         putchar('\n');
     else
         putchar(c);
}

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477348

Here's a much, much simpler solution:

#include <string>
#include <fstream>
#include <iostream>

int main()
{
    std::ifstream infile("thisfile.txt");

    for (std::string word; infile >> word; )
    {
        std::cout << "Got one word: " << word << std::endl;
    }
}

Upvotes: 3

Related Questions