Returning a vector of strings - c++

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.

Related

Type 'string' could not be resolved

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

Visual Studio 2015: Getting "non standard syntax, use '&' to create a pointer to member" error

Super confused as to what is throwing the error when I try to compile my code. I'm currently trying to test a function I wrote by printing out the values it should extract from a file.
gameboard.cpp
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include "error.h"
using namespace std;
int boardDim(ifstream & inputFile, unsigned int x, unsigned int y) {
inputFile.open; //error is thrown here
if (!(inputFile.is_open())) {
throw fileNotOpen;
}
else {
stringstream output(inputFile.getline); //error is also thrown here
if (output >> x) {
if (output >> y) {
return success;
}
return secBoardVarErr;
}
return firstBoardVarErr;
}
cout << x << endl;
cout << y << endl;
}
gameboard.h
#ifndef GAMEBOARD_H
#define GAMEBOARD_H
#include <iostream>
using namespace std;
//takes in dimensions of board from file
int boardDim(ifstream &, unsigned int, unsigned int);
#endif !GAMEBOARD_H
main function
#include "stdafx.h"
#include "functions.h"
#include "gamepieces.h"
#include "gameboard.h"
#include "error.h"
int main(int argc, char * argv[])
{
ifstream x("test.txt");
int test = 0;
cout << boardDim(x, 0, 0) << endl;
return success;
}
I'm only testing the function I declared and defined in the gameboard header and source files, so the other included files will be used in the future but have already been tested and are not throwing errors when I compile and run it.
Thank you!
inputFile.open is a function, same with inputFile.getline, so what you have here is a syntactic error. The correct syntax is:
inputFile.open()
and
inputFile.getline()

Standard functions and operations not working in class constructor

I am trying to make my first class with a constructor and it seems to be acting strangely.
My class is derived from filebuf and for some reason, I am unable to open it in the constructor.
I tried to add a cout statement for debugging, but the << operator is not recognized.
#include <iostream>
#include "bin.h"
int main()
{
bin myBin("e:\Temp\test.txt");
system("PAUSE");
return 0;
}
bin.h
#pragma once
#include <fstream>
#include <cstdlib>
#include <cstring>
class bin : private std::filebuf {
int buffSize = 1000;
char* buffer;
unsigned int length;
short int buffCounter;
public:
bin(std::string fileName)
{
open(fileName.c_str(), std::ios::in | std::ios::out | std::ios::trunc);
if (!is_open())
std::cout << "ERROR: failed to open file " << fileName << std::endl;
//set all IO operations to be unbufferred, buffering will be managed manually
setbuf(0, 0);
//create buffer
buffer = new char[buffSize];
};
virtual ~bin()
{
delete buffer;
};
};
bin myBin("e:\Temp\test.txt");
You have to correct above line as follows:
bin myBin("e:\\Temp\\test.txt");
DEMO: http://cpp.sh/7b4k
It looks like you need:
#include <iostream>
To use std::string you need:
#include <string>
The iostream include may have forward-declared std::string but without the full definition you don't get operator<< (or c_str()).
Some other answerers may be unable to reproduce your problem because different standard libraries might have their iostream fully do #include <string> (this is permitted but not required).
std::cout << "ERROR: failed to open file " << fileName << std::endl;
Should be
std::cout << "ERROR: failed to open file " << fileName.c_str() << std::endl;
std::cout doesn't always accept std::string but does accept const char *

NetBeans not recognizing C++ class members at build+run

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?

output list of files from popen to ifstream.open

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;
}
}
}