Good Day all!

Looking for a little help here.
I have to open a file containing a few words, some of which ending in "ed"
and print the only the words ending in "ed" back to file.

Here is what I have so far. I cannot seem to open the file, and also need to understand
how to read the string into the file correctly.

I seem to be missing the linkage between opening the file and reading the array into it.
Thanks for helping my poor sould.

Please refrain from short responses, in which you assume I know exactly what you are talking about.
I am hardly a nerd and far from a c++ guru. SOMEDAY.

#include <stdio.h>
#include <string.h>

int main( void )
 {

int i; /* loop counter */
 int length; /* length of current string */
char array[ 5 ][ 20 ] = {0}; /* 5 strings from user */
 char filename [100];
 FILE* fileptr;

 printf ("Please enter the file to open:");
 scanf_s ("%s", filename);

 fileptr = fopen (filename, "r");

 if (fileptr == NULL)
 {
     printf ("Unable to open '%s' for input. \n", filename);
 }

 else 
 {
     while (!feof(fileptr))
 /* read in 5 strings from user */
 for ( i = 0; i <= 4; i++ ) {
 printf( "\nThe strings ending with \"ED\" are:\n" );
 }
 /* loop through 5 strings */
 for ( i = 0; i <= 4; i++ ) {

 /* find length of current string */
length = strlen( &array[ i ][ 0 ] );

 /* print string if it ends with "ED" */
 if ( strcmp( &array[ i ][ length - 2 ], "ED" ) == 0 ) {
printf( "%s\n", &array[ i ][ 0 ] );

fclose (fileptr);


} /* end if */

}//end for //

} //end else//

 return 0; 

} //end main//

Dani AI

Generated

Quick, practical fix and explanation for (building on ’s suggestion to use C++ streams).

Your original C code never actually reads strings from the opened file, uses feof() incorrectly, and performs a substring/strcmp without ensuring the string is long enough (that causes out‑of‑range access). is right that C++ iostreams make this simpler. Below is a small, robust example that: reads a filename from stdin, tokenizes by whitespace, strips trailing punctuation, checks length before testing the last two letters (case‑insensitive), collects matches, and writes them to a safe output file (original preserved).

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>

static inline void to_lower(std::string &s) {
    std::transform(s.begin(), s.end(), s.begin(),
                   [](unsigned char c){ return std::tolower(c); });
}

int main() {
    std::string filename;
    std::getline(std::cin, filename);
    std::ifstream in(filename);
    if (!in) { std::cerr << "Cannot open input file\n"; return 1; }

    std::vector<std::string> ed_words;
    std::string token;
    while (in >> token) {
        while (!token.empty() && std::ispunct(static_cast<unsigned char>(token.back())))
            token.pop_back();                // remove trailing punctuation
        if (token.size() < 2) continue;      // avoid substr out of range

        std::string tail = token.substr(token.size() - 2);
        to_lower(tail);
        if (tail == "ed") ed_words.push_back(token);
    }

    std::ofstream out(filename + ".ed");
    for (const auto &w : ed_words) out << w << '\n';
}

Notes and troubleshooting

  • Use while (in >> token) or while (std::getline(...)) instead of feof().
  • Strip punctuation (commas, periods) before testing the tail.
  • Always check token.size() >= 2 before taking the last two chars.
  • To overwrite the original file safely, write to a temp file then rename it after successful write.
  • If you need case-insensitive matching, convert to lower (example above).

This should get a working, safe program; tweak the token-cleaning rules if your input contains quotes or embedded punctuation.

Recommended Answers

All 3 Replies

There is a related article link on this page (i'm assuming you see it too) File Display Proram , Take a close look at the includes, the use of ifstream object for reading files, namespace std, cout etc.. That is the std c++ way of writing code. i'm guessing you've just started so it's best to get the basics right before we get to the logical errors.

Thanks Agni, I now have this but am stuck halfway through the program on what contents to input.

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

void find_ed_words(vector <string> &words, string &thefile)
{

  string a_line, a_word;
  ifstream datafile ("Steve1.txt");
  std::stringstream ss;

  datafile.open(thefile, ifstream::in);

  while (datafile.good())
  {
      std::getline(datafile, a_line, '\r');
      ss << a_line;
      while(ss >> a_word) 
      {
          cout << a_word << endl;
          if (a_word.substr(a_word.length()-2,2) == "ed")
          {
              words.push_back(a_word);
          }
      }
  }
}

void append_to_file(vector <string> &words, string &thefile)
{
}


int main () {

string filename = "Steve1.txt";
vector <string> edwords;
find_ed_words(edwords, filename);
long i;
cout << "\nEd words:\n";
for (i = 0; i < edwords.size(); i++) 
{ // Just so you can see the words have been read and parsed.
    cout << edwords[i] << endl;
}
append_to_file(edwords, filename);

  return 0;
}

So it looks like you have managed to read the words ending with 'ed' in the vector ? Now in 'append_to_file' you have to do a similar operation as above but instead of ifstream you need to create an object of 'ofstream' and open the file in 'ios::out' mode and write the vector into it. ios::out mode overwrites the contents of the file while ios::app mode will append to the end of the file. Pseudo-code would look something like

std::ofstream outfile("myfile",ios::out);
if file is open{
    loop for vector
        outfile << vector[index];
}
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.