0

I'm trying to write a function to do these things:

  • read a file
  • for each line, add all ASCII values of every character
  • check if sum of those values is a prime number
  • return how many prime numbers were in file

Here are the functions:

#include <math.h>
#include <iostream>
#include <fstream>

using namespace std;

bool isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; i*i <= n; i++)
        if (n % i == 0) return false;
    return true;
}

int checkFile () {
    ifstream napis("data.txt");
    string line;
    int primesCount = 0;

    while (napis.is_open() && getline(napis, line)) {
        int lineLen = line.length();
        int sum = 0;
        for (int i = 0; i < lineLen; i++) {
            sum += (int)line[i];
        }

        if (isPrime(sum)) primesCount++;
    }

    return primesCount;
}

Each line in file is a string with only capital letters, for example AQUALFJMAGDDSNO

I have a file of 1000 lines like that above, and I know there are 122 prime numbers, but this function returns 153.

I know there are many other ways to to this and I've found solutions on the internet, but why isn't this function working properly?

Chris Kraszewski
  • 681
  • 10
  • 19

0 Answers0