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_ */
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
Related
I am trying to print the data located in the weapon.obj file, but it's not working.
Compiler Error: error: no matching function for call to
'getline(std::ifstream&)'|
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream render_weapon_OBJ ("weapon.obj");
render_weapon_OBJ << ("Weapon Names");
render_weapon_OBJ.close();
ifstream execute_weapon_OBJ ("weapon.obj");
while (getline(execute_weapon_OBJ))
{
cout << execute_weapon_OBJ << '\n';
}
execute_weapon_OBJ.close();
}
You must specify where to read the data and use that for printing.
#include <iostream>
#include <fstream>
#include <string> // add this to use std::string
using namespace std;
int main()
{
ofstream render_weapon_OBJ ("weapon.obj");
render_weapon_OBJ << ("Weapon Names");
render_weapon_OBJ.close();
ifstream execute_weapon_OBJ ("weapon.obj");
string weapon; // add this for read buffer
while (getline(execute_weapon_OBJ, weapon)) // add where to read
{
cout << weapon << '\n'; // print what was read instead of the stream
}
execute_weapon_OBJ.close();
}
May be this is the solution you are looking for
You need a variable to store the line read from the file and you need to print the variable not the variable used to initialize the file stream.
The error is in the while loop[The new code is below]
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string line;
ofstream render_weapon_OBJ ("weapon.obj");
render_weapon_OBJ << ("Weapon Names");
render_weapon_OBJ.close();
ifstream execute_weapon_OBJ ("weapon.obj");
while(getline(execute_weapon_OBJ,line))
{
cout << line << '\n';
}
execute_weapon_OBJ.close();
}
I want to read some input files in my c++ code and I want to define the path of input files as a string and then combine it with file names. How can I do this? (Input_path + filename.dat)
#include <filesystem> //C++ 17
#include <iostream>
namespace fs = std::filesystem;
using namespace std;
void main()
{
string dir("c:\\temp");
string fileName("my_file.txt");
fs::path fullPath = dir;
fullPath /= fileName;
cout << fullPath.c_str() << endl;
}
You would use something like:
string path ("yourFilePath");
string filename ("filename");
You could then open the file like this:
ifstream inputFileStream;
inputFileStream.open(path + fileName);
Depending on your requirements, you will have to decide whether to use formatted or unformatted input when reading. I would read this for more information regarding that.
Cocatenation referenced from: C++ string concatenation
Reading referenced from: C++ read and write with files
Try any of these codes:
#include <iostream>
#include <string>
#include <fstream>
int main() {
std::string filepath = "D:/location/";
filepath+= "filename.dat";
std::ifstream fp;
fp.open(filepath.c_str(),std::ios_base::binary);
....PROCESS THE FILE HERE
fp.close();
return 0;
}
or
#include <iostream>
#include <string>
#include <fstream>
int main() {
std::string filepath = "D:/location/";
std::ifstream fp;
fp.open((filepath+"filename.dat").c_str(),std::ios_base::binary);
...............
fp.close();
return 0;
}
or use std::string::append
#include <iostream>
#include <string>
#include <fstream>
int main() {
std::string filepath = "D:/location/";
std::ifstream fp;
fp.open((filepath.append("filename.dat")).c_str(),std::ios_base::binary);
fp.close();
return 0;
}
I'm a bit confused with all the namespaces for vector and how to properly return a vector of strings in my class. Here is the code:
main.cpp
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <string>
#include "lab1.h"
using namespace std;
readwords wordsinfile;
words wordslist;
int main ( int argc, char *argv[] )
{
if ( argc != 2 ) {
// Looks like we have no arguments and need do something about it
// Lets tell the user
cout << "Usage: " << argv[0] <<" <filename>\n";
exit(1);
} else {
// Yeah we have arguements so lets make sure the file exists and it is readable
ifstream ourfile(argv[1]);
if (!ourfile.is_open()) {
// Then we have a problem opening the file
// Lets tell the user and exit
cout << "Error: " << argv[0] << " could not open the file. Exiting\n";
exit (1);
}
// Do we have a ASCII file?
if (isasciifile(ourfile)) {
cout << "Error: " << argv[0] << " only can handle ASCII or non empty files. Exiting\n";
exit(1);
}
// Let ensure we are at the start of the file
ourfile.seekg (0, ios::beg);
// Now lets close it up
ourfile.close();
}
// Ok looks like we have past our tests
// Time to go to work on the file
ifstream ourfile2(argv[1]);
wordsinfile.getwords(ourfile2);
lab1.h
#ifndef LAB1_H
#define LAB1_H
bool isasciifile(std::istream& file);
class readwords {
public:
int countwords(std::istream& file);
std::vector<std::string> getwords(std::istream& file);
};
class words {
public:
void countall( void );
void print( void );
};
#endif
lab1.cpp
#include <fstream>
#include <iostream>
#include <map>
#include "lab1.h"
#include <vector>
using std::vector;
#include <string>
using namespace std;
vector<string> readwords::getwords(std::istream& file) {
char c;
string aword;
vector<string> sv;
int i = 0;
while(file.good()) {
c = file.get();
if (isalnum(c)) {
if(isupper(c)) {
c = (tolower(c));
}
if(isspace(c)) { continue; }
aword.insert(aword.end(),c);
} else {
if (aword != "") {sv.push_back(aword);}
aword = "";
i++;
continue;
}
}
return sv;
}
Here is the error from compiling.
g++ -g -o lab1 -Wall -pedantic main.cpp lab1.cpp
In file included from lab1.cpp:4:0:
lab1.h:9:4: error: ‘vector’ in namespace ‘std’ does not name a type
lab1.cpp:48:54: error: no ‘std::vector<std::basic_string<char> > readwords::getwords(std::istream&)’ member function declared in class ‘readwords’
make: *** [lab1] Error 1
Why do I get this error and how do I fix it. Thank you for any help you can provide.
Ryan
You have to #include <vector> in the header file as well. Actually, including it in the header is enough, as all files including that header will implicitly also include <vector>.
The thing is your include order is:
#include "lab1.h"
#include <vector>
and since you use std::vector in the header (before including it) you get the error. Reversing the include order would fix the compilation error, but doesn't solve the underlying error - that lab1 uses symbols that weren't defined yet. The proper fix is to include <vector>.
The compiler looks at code in the order it's written. That also applies to #include directives: the contents of the file are treated as if they had been written in the file that #include's them. As #LuchianGrigore has mentioned, the best solution is to add
#include <vector>
to "lab1.h". But you could hide the problem by moving the #include <vector> in "lab1.cpp" so that it comes before the #include "lab1.h". That would make the error go away, because the compiler would have already read` before it started to read "lab1.h". That's not what you should do, but it's the kind of thing that can happen accidentally and hide the actual problem.
I am still fairly new to NetBeans, and am writing code for class in C++. I am currently on my third project, and I have run into an error I can't seem to resolve when trying to compile+run my project. I have quadruple-checked my code, going so far as to copy code from a previous project. I have tried quiting, rebooting the computer, and starting NetBeans up again. I ran CppCheck on my code and it found no errors.
The error message:
build/Debug/MinGW-Windows/main.o: In function `main':
C:/Users/Martin/Documents/NetBeansProjects/Lab3/main.cpp:52: undefined reference to `Dictionary::Dictionary()'
C:/Users/Martin/Documents/NetBeansProjects/Lab3/main.cpp:52: undefined reference to `Dictionary::~Dictionary()'
I tried copying code from a previous project, and even with the exact same code as a previous project which works, it's still having this problem. Basically, the build is failing to recognize the Dictionary class.
What things can I check that might cause this problem? Any obscure (or even obvious) settings I can check? Should I just start a new project and copy my code over?
Edit: Adding main():
#include <cstdlib>
#include <iostream>
#include "Dictionary.h"
using namespace std;
/*
* argv[1] dictionary file
* argv[2] boggle board file
* argv[3] output file
*/
int main(int argc, char** argv) {
if (argc > 3) {
Dictionary dict;
dict.loadDictFile(argv[1]);
} else {
cout << "Not enough arguments. Needed: ./lab3 [dictionary file] "
"[board file] [output file]" << endl;
}
return 0;
}
And Dictionary.h:
#ifndef DICTIONARY_H
#define DICTIONARY_H
#include <string>
#include <set>
using namespace std;
class Dictionary {
public:
Dictionary();
Dictionary(const Dictionary& orig);
virtual ~Dictionary();
virtual void loadDictFile(char * fileName);
virtual bool find(string word);
private:
set<string> dict;
set<string> fullDictionary; // Contains all words, not just those 4+ char long.
};
#endif /* DICTIONARY_H */
And Dictionary.cpp:
#include "Dictionary.h"
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <set>
//using namespace std;
Dictionary::Dictionary() {
}
Dictionary::Dictionary(const Dictionary& orig) {
dict = orig.dict;
fullDictionary = orig.fullDictionary;
}
Dictionary::~Dictionary() {
}
void Dictionary::loadDictFile(char* fileName) {
ifstream infile;
infile.open(fileName);
if (infile) {
while(!infile.eof()) {
string line;
getline(infile, line);
fullDictionary.insert(line);
if (line.size() > 3) {
dict.insert(line);
}
}
} else {
cout << "Dictionary File not loaded: " << fileName << endl;
}
}
bool Dictionary::find(string word){
if (dict.find(word) != dict.end()) {
return true;
} else {
return false;
}
}
Found my problem. Netbeans didn't consider the Dictionary class to be part of my project, so it wasn't compiling Dictionary.cpp. I added it in the Project window by right-clicking the Source Files folder and using Add existing item... menu option. Now it compiles fine.
Does anyone know why the class wouldn't be added if I used Netbean's New File interface and added to the project specifically?
Basically I need to open and read a list of files I get from another command.
For each line of output of popen
open a file usen ifstream.open
it compiles and if I put the file name directly it works fine, but it doesn't do anything when using popen output. I've seen questions like this but none of this particular way of giving filenames.
here's the code:
#include <iostream>
#include <sqlite3.h>
#include <stdio.h>
#include <fstream>
using namespace std;
int main () {
ifstream singlefile;
FILE *filelist;
char filename[512];
string progline;
if(!(filelist = popen("find `pwd` -name \"*.js\"", "r"))){
return 1;
}
while( fgets(filename, sizeof(filename), filelist)!=NULL)
{
cout << filename;
singlefile.open(filename, ifstream::in);
while ( singlefile.good() )
{
getline (singlefile,progline);
cout << progline << endl;
}
singlefile.close();
}
pclose(filelist);
return 0;
}
next step would be not open each file inside the loop but to store the file list and then open each file.
Thanks
fgets keeps the trailing newline, resulting in a filename of a non-existing file. Also the stream state is only updated after reading. If I replace the while body with the following code, it works for me:
cout << filename;
size_t len = strlen(filename);
// chop off trailing newline
if (len > 1 && filename[len - 1] == '\n') filename[len - 1] = 0;
singlefile.open(filename, ifstream::in);
while ( getline(singlefile, progline) )
{
cout << progline << endl;
}
singlefile.close();
If you actually want to iterate through a list of files, I'd use Boost.Filesystem, which has a nice C++ interface, works for all filenames (even for those with newlines), and is platform-independent.
If this actually is only an example and your actual command is not find, there is still some room for simplification. Here is a suggestion that uses Boost.Iostreams to get rid of most of the C function calls (it would be great to have a device source reading from a process's standard output, but Boost.Iostreams lacks that):
#include <cstdio>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <stdio.h>
#include <boost/noncopyable.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
using namespace std;
namespace io = boost::iostreams;
class Popen: private boost::noncopyable {
public:
explicit Popen(const char* command):
m_stream(popen(command, "r")) {
if (!m_stream) throw runtime_error("popen failed");
}
~Popen() {
pclose(m_stream);
}
FILE* stream() const {
return m_stream;
}
private:
FILE* m_stream;
};
int main() {
Popen pipe_wrapper("find `pwd` -name \"*.cpp\"");
io::file_descriptor_source pipe_device(fileno(pipe_wrapper.stream()), io::never_close_handle);
io::stream<io::file_descriptor_source> pipe_stream(pipe_device, 0x1000, 0x1000);
string filename;
while (getline(pipe_stream, filename)) {
cout << filename << endl;
ifstream file_stream(filename.c_str(), ifstream::in);
string progline;
while (getline(file_stream, progline)) {
cout << progline << endl;
}
}
}