So I'm supposed to copy the word "computer" or "computers" from the text of one file and past the word each time to the new file. It compiles but it doesnt run right. Any input would be great.

#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

int main()
{
        char filename, filename2, word[20]; //char to read the input and output files as well as word from the file
        ofstream fout;//output file
        ifstream fin;//input file

        cout << "Enter you input file:";
        cin>>filename;//stores the input filename

        fin.open("filename");//open input file

        cout << "Enter your output filename";
        cin>>filename2;//stores output filename

        do
        {
                if(strcmp("COMPUTER", word) || strcmp ("COMPUTERS", word))//looks for both computer and computers in file
                {

                fout.open ("filename2");//open output file
                fout<<word;//prints the word in the output file
                }

        }while(word);

        fin.close();//closes input file
        fout.close();//closes output file
return 0;
}

Recommended Answers

All 3 Replies

do
        {
                if(strcmp("COMPUTER", word) || strcmp ("COMPUTERS", word))//looks for both computer and computers in file
                {

                fout.open ("filename2");//open output file
                fout<<word;//prints the word in the output file
                }
// read the word here from the input file in 'word'
        }while(word);//curently it is a bad loop

is not doing the job. You need to read word by word and then compare. Also there is no need re opening the output file fout.open ("filename2");//open output file .
You can find several examples in this forum on how to read a word from a file.

-Prateek

There are errors in reading from and writing to a file and do-while results in an infinite loop.

>> char filename, filename2, word[20];
You are attempting to tread char as if it were std::string. My suggestion is to get rid of those c-style character arrays and use the easier-to-use std::string instead

std::string filename, filename2, word;

...
      cout << "Enter your output filename";
      getline(filename2,cin);//allow filename to contain spaces
      ofstream out(filename2.c_str());
      while( fin >> word)
      {
          if( word == "COMPUTER" || word == "COMPUTERS")
              fout << word;

      }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.