-1

Im new to coding c++ and i am trying to call a function from another file to check if the string containing the text file is made up of alphabetic characters, but for some reason it is not working.

I am getting errors in my ap.cpp file saying

Invalid arguments ' Candidates are: bool is_alpha(?) ' and

‘is_alpha’ cannot be used as a function

and also errors in my header file saying

Type 'string' could not be resolved

MY CODE:

AP.cpp

#include <iostream>
#include <fstream>
#include <string>
#include "functions.h"
using namespace std;

int main () {
  string line;
  string textFile;
  ifstream myfile ("encrypted_text");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
        textFile += line;
    }
    myfile.close();
  }

  else cout << "Unable to open file";

  bool check = is_alpha(textFile);
  if (check){
      cout << "true";
  } else cout << "false";

  return 0;
}

checkFunctions.cpp

#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include "functions.h"
using namespace std;

bool is_alpha (string str) {
    for(int i=0; i < str.size(); i++)
    {
        if( !isalpha(str[i]) || !isspace(str[i]))
        {
            return true;
        }
    }
    return false;
}

functions.h

#ifndef FUNCTIONS_H_
#define FUNCTIONS_H_
#include <string>

bool is_alpha(string str);



#endif /* FUNCTIONS_H_ */
yanr
  • 1
  • 3
  • 2
    `std::string` in your header file (because there were no `using namespace std;` prior to that point), not `string`. I recommend reading about namespaces a little. – yeputons Jan 19 '21 at 16:58
  • 1
    Everyone who's "new to coding c++" will do themselves a big, big favor if they completely forget [that `using namespace std;` is part of C++ and make a promise to never use it in their code](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) at least until they gained sufficient experience to understand all the implications. – Sam Varshavchik Jan 19 '21 at 17:02

1 Answers1

0

It'll be the best if you not use using namespace std; until you have a proper understanding about the language and its implications. If you were wondering what using namespace does is, it basically sets the content in the namespace and puts it to the global namespace (in which you don't need to specify where it comes from, in this its std and the way to call it is std::).

The error is because the compiler doesn't know where the string in bool is_alpha(string str); comes from. So to solve this, take my first advice to consideration and you can specify where it comes from like this: bool is_alpha(std::string str);.

Plus you don't need to add the libraries included in a header file again in the source file. This means that you can remove the #include <string> from AP.cpp and checkFunctions.cpp.

More about header files: https://stackoverflow.com/a/9224641/11228029

D-RAJ
  • 3,263
  • 2
  • 6
  • 24