0

So I'm trying to check a string and see if it:

  1. has 8 or more chars
  2. has at least one uppercase letter
  3. has at least one lowercase letter
  4. has at least one of the following chars .,?!;:_!@#

Here's my code:

#include <fstream>
#include <string.h>
using namespace std;
char a[51];
int n,i,countcheck,hardc;
int main()
{
    ifstream fin("parole.in");
    ofstream fout("parole.out");
    fin >> n;
    for (i=1;i<=n;i++)
    {
        fin >> a;
        if(strlen(a)>=8)countcheck++;
        if(strchr(a,'ABCDEFGHIJKLMNOPQRSTUVWXYZ'))countcheck++;
        if(strchr(a,'abcdefghijklmnopqrstuvwxyz'))countcheck++;
        if(strchr(a,'.,?!;:_!@#'))countcheck++;
        if (countcheck==4)hardc++;
        countcheck=0;
    }
    fout << hardc << '\n';
    fin.close();
    fout.close();
    return 0;
}

Thanks in advance!

Elie Génard
  • 1,673
  • 3
  • 21
  • 34
AlexxA
  • 21
  • 2
    `'ABCDEFGHIJKLMNOPQRSTUVWXYZ'` isn't a valid string literal. This should be `"ABCDEFGHIJKLMNOPQRSTUVWXYZ"`. – πάντα ῥεῖ Mar 26 '15 at 15:31
  • Oh,but it still doesn't work. Now it says invalid conversion from const char* to int. – AlexxA Mar 26 '15 at 15:34
  • `strchr` takes a character as it's second argument. It returns the pointer to the first instance of this character found. If you want to find any of the desired characters you'd better iterate through the string manually and check its existence in your set of characters (possibly using the very same `strchr`). – Predelnik Mar 26 '15 at 15:37
  • 3
    Also since it's c++, you'd better use `std::string` and algorithms like `std::find_if` or `std::count_if`. – Predelnik Mar 26 '15 at 15:39

1 Answers1

2

In C++, favour using std::string to character arrays. You can then use algorithms like std::any_of and/or std::string::find_first_of. Here is an example using both:

#include <string>
#include <algorithm>

bool checkString(const std::string& str)
{
    return str.length() >= 8
        && std::any_of(str.begin(), str.end(), ::isupper)
        && std::any_of(str.begin(), str.end(), ::islower)
        && str.find_first_of(".,?!;:_@#") != std::string::npos;
}

Usage of checkString:

#include <iostream>

int main()
{
    std::string tests[] {
        "Test.123",
        "Test#@#$",
        ".,?!;:_@",
        "7Chars!",
        "abcd.123",
        "ABCD.123"
    };

    for (const auto& s : tests)
        std::cout << s << (checkString(s) ? " \t-GOOD\n" : " \t-BAD\n");
}

Output:

Test.123    -GOOD
Test#@#$    -GOOD
.,?!;:_@    -BAD
7Chars!     -BAD
abcd.123    -BAD
ABCD.123    -BAD

Live Demo

Julian
  • 1,688
  • 1
  • 12
  • 19