R
R
romentigo2018-05-18 18:27:28
C++ / C#
romentigo, 2018-05-18 18:27:28

C++ - how to count the number of lines from a file that start and end with the same character?

The program is almost ready, but I can not figure out how to proceed. If the first line starts and ends with the same character, then the counter works, but not with the rest of the lines. Maybe there is an error in the file read cycle?

#include "stdafx.h"
#include <iostream>

using namespace std;

void create_file(FILE* f, char* name)
{
  char s[1000];
  f = fopen(name, "wt"); 
  if (f == NULL) { cout << "Cannot create file\n"; return; }
    cout << "Input strings" << endl;
  do 
  { 
    gets_s(s, 1000); 
    fputs(s, f); 
    fputs("\n", f); 
  } 
  while (strcmp(s, ""));
    fclose(f); 
}

void view_file(FILE* f, char* name)
{
  char s[1000];
  f = fopen(name, "rt"); 
  if (f == NULL) 
  {
    cout << "Cannot open file to veiw\n"; 
    return; 
  }
  cout << "\nView file" << endl;
  while (fgets(s, 100, f)) 
  { 
    s[strlen(s) - 1] = '\0'; 
    puts(s); 
  }
  fclose(f);
}

int Strings(FILE* f, char* name)
{
  char s[1000];
  int kol = 0;

  f = fopen(name, "rt");
  if (f == NULL) 
  { 
    cout << "Cannot open file\n"; 
    return 0; 
  }
  while (fgets(s, 1000, f))
  {
    if (s[0] == s[strlen(s) - 1])
    {
      kol++;
    }
  }
  return kol;
}

int main()
{
  FILE* f = NULL;
  char* name = "file.txt";

  create_file(f, name);
  view_file(f, name);
  cout << "Num of strings: " << Strings(f, name) << endl;

  system("pause");
    return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2018-05-19
@res2001

The debugger will help you!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question