Reputation: 1344
I'm trying to abstract out a method from a simple program. This method tests the length of an array against a predeclared CAPACITY constant, and spits out an error message if conditions aren't met. However, I'm having trouble creating a header file with a .cpp file to hold the method.
the header file:
//arrayHelper.h
#ifndef ARRAYHELPER_H
#define ARRAYHELPER_H
void arrayLengthCheck(int & length, const int capacity, string prompt);
#endif // ARRAYHELPER_H
the code file:
//arrayHelper.cpp
#include <iostream>
#include <string>
#include "arrayHelper.h"
using namespace std;
void arrayLengthCheck(int & length, const int capacity, string prompt)
{
// If given length for array is larger than specified capacity...
while (length > capacity)
{
// ...clear the input buffer of errors...
cin.clear();
// ...ignore all inputs in the buffer up to the next newline char...
cin.ignore(INT_MAX, '\n');
// ...display helpful error message and accept a new set of inputs
cout << "List length must be less than " << capacity << ".\n" << prompt;
cin >> length;
}
}
Running this main.cpp file that contains #include "arrayHelper.h"
errors out that string is not declared
in the header file. Including string in the header file has no effect, but #include "arrayHelper.cpp"
results in a redefinition of the method. How should I approach this problem?
Upvotes: 0
Views: 200
Reputation: 45410
string
is used in header file but can't find the symbol.
Move #include <string>
to arrayHelper.h
and replace all string
with std::string
Side note:
call using namespace std;
locally is idiomatic way, and pass prompt
by reference can elide one copy. Below is slightly enhancement to your code:
arrayHelper.h
#ifndef ARRAYHELPER_H
#define ARRAYHELPER_H
#include <string>
void arrayLengthCheck(int & length, const int capacity, const std::string& prompt);
#endif // ARRAYHELPER_H
arrayHelper.cpp
#include <iostream>
#include "arrayHelper.h"
void arrayLengthCheck(int & length, const int capacity, const std::string& prompt)
{
using namespace std;
// If given length for array is larger than specified capacity...
while (length > capacity)
{
// ...clear the input buffer of errors...
cin.clear();
// ...ignore all inputs in the buffer up to the next newline char...
cin.ignore(INT_MAX, '\n');
// ...display helpful error message and accept a new set of inputs
cout << "List length must be less than " << capacity << ".\n" << prompt;
cin >> length;
}
}
Upvotes: 2
Reputation: 227418
You should #include <string>
in the header, and refer to string
as std::string
, since using namespace std
would be a bad idea in a header file. In fact it is a bad idea in the .cpp
too.
//arrayHelper.h
#ifndef ARRAYHELPER_H
#define ARRAYHELPER_H
#include <string>
void arrayLengthCheck(int & length, const int capacity, std::string prompt);
#endif // ARRAYHELPER_H
Upvotes: 5