struct in header file not recognized - c++

practice.h
struct CandyBar
{
string name;
double weight;
int calories;
};
practice.cpp
#include <iostream>
#include <string>
#include "practice.h"
using namespace std;
int main()
{
CandyBar snacks{ "Mocha Munch", 2.3, 350 };
cout << snacks.name << "\t" << snacks.weight << "\t" << snacks.calories << endl;
return 0;
}
when I build the solution, I get the errors:
practice.h(5): error C2146: syntax error : missing ';' before identifier 'name'
practice.h(5): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2440: 'initializing' : cannot convert from 'const char [12]' to 'double'
There is no context in which this conversion is possible
practice.cpp(20): warning C4244: 'initializing' : conversion from 'double' to 'int', possible loss of data
practice.cpp(20): error C2078: too many initializers
practice.cpp(22): error C2039: 'name' : is not a member of 'CandyBar'
practice.h(4) : see declaration of 'CandyBar'
what is cause of all the errors? why won't the variables get recognized as fields of the struct?

The issue is that when the headers parser there is no type string.
The best way is to include the namespace e.g.
struct CandyBar
{
std::string name;
double weight;
int calories;
};
This does not show up in the cpp file as you have using namespace std;
You could put the using line before the #include "practice.h" but that is considered bad style as the header is now not self contained and you could have namespace conflicts.

You need to include in practice.h.
Like so:
#include <string>
struct CandyBar
{
std::string name; // And also std:: before string, as Praetorian pointed out
double weight;
int calories;
};

The include is not required, but you must either import namespace std or fully qualify its usage. So either repeat the using statement or declare name as type std::string.

You should use "#ifndef", "#define". Because maybe header files can call to initialize some times. Therefore you take errors. Look this: C++’ta Seperated Compilation II – Header File Kullanmak

Related

C++ .h and .cpp file separate

I'm trying to separate my c++ code to one header and one cpp file, but the interpreter showing some errors.
Here is my code:
Password.h:
#ifndef PASSWORD_H
#define PASSWORD_H
class Password {
private:
string aliasName_;
int hashOfPassword_;
public:
void setAliasName(string aliasName);
void setHashOfPassword(int hashOfPassword);
string getAliasName() { return aliasName_; }
int getHashOfPassword() { return hashOfPassword_; }
};
#endif
Password.cpp:
#include <string>
#include "Password.h"
using std::string;
void Password::setAliasName(string aliasName) {
aliasName_ = aliasName;
}
void Password::setHashOfPassword(int hashOfPassword) {
hashOfPassword_ = hashOfPassword;
}
Errors:
Error C2065 'aliasName_': undeclared identifier X\password.cpp 7
Error C2511 'void Password::setAliasName(std::string)': overloaded member function not found in 'Password' X\password.cpp 6
Error C3646 'aliasName_': unknown override specifier X\password.h 6
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int X\password.h 6
Error C2061 syntax error: identifier 'string' X\password.h 9
Error C3646 'getAliasName': unknown override specifier X\password.h 11
Error C2059 syntax error: '(' X\password.h 11
Error C2334 unexpected token(s) preceding '{'; skipping apparent function body X\password.h 11
Anyone have any ideas ?
You need to move using std::string before the declaration of your class:
#ifndef PASSWORD_H
#define PASSWORD_H
#include <string>
using std::string;
class Password {
…
and remove it from your .cpp file.
Also, you might want to use #pragma once instead of the traditional #ifndef/#define/#endif and finally you might want to make your argument and methods const when need be.
You need to move
#include <string>
using std::string;
To inside Password.h, you can then remove these two lines from Password.cpp.
Just add std:: to every string in your header file and remember, you should never use using or using namespace there! You should also include all the headers to the file in which you use them.

first time using .h and multiple .cpp files in one project, errorssss :(

second post on StackOverflow. I just have some general questions as to why my program is acting the way it is, I don't want help in completing it I was just absent from class on Friday and apparently I missed a lot.
I'm tasked to design a program that contains 3 .cpp and 2 .h files, in essence it will search and sort through arrays of strings using the bubble sort, insertion sort, selection sort methods and sequential and binary search. We are then supposed to benchmark each method to figure out which is the fastest.
I am just confused as to why the compiler keeps yelling at me, it's not making much sense I've been sitting here for about an hour fiddling around with different options or typing the code in differently but to no avail.
My header file
const int NOT_FOUND = -1;
int sequentialSearch(string a[], string needle, int length );
JohnSearch.cpp
#include "JohnSearch.h"
#include <string>
int sequentialSearch(string copied[], string needle, int length)
{
int i; // iteration variable
// look at every element to see if it is the same as needle
for( i = 0; i < length; i++ )
if( copied[i] == needle )
return i;
return NOT_FOUND;
}
TestSearch.cpp
#include "JohnSearch.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
/*
** printArray(title,a,length): print out title and then the contents of array a
*/
void printArray(string title, string ref[], int length )
{
int i; // array iteration
cout << title << ": \n";
for( i = 0; i < length; i++ )
cout<<setw(20)<<ref[i]<<"\n";
}
int main(void)
{
string reference[]={"John", "Allen", "Kevin", "Elisabeth"};
const int SZ=sizeof(reference)/sizeof(reference[0]);
string copied[SZ];
printArray("Reference", reference, SZ);
// sequential search (on unsorted array)
cout<<"Search.sequential(ref,Kevin):\t"<<sequentialSearch(reference, "Kevin", SZ)<<endl;
system("Pause");
return 0;
}
Errors
johnsearch.h(2): error C2065: 'string' : undeclared identifier
johnsearch.h(2): error C2146: syntax error : missing ')' before identifier 'a'
johnsearch.h(2): error C2059: syntax error : ')'
testjohnsearch.cpp(28): error C3861: 'copyArray': identifier not found
testjohnsearch.cpp(31): error C2064: term does not evaluate to a function taking 3 arguments
johnsearch.h(2): error C2065: 'string' : undeclared identifier
johnsearch.h(2): error C2146: syntax error : missing ')' before identifier 'a'
johnsearch.h(2): error C2059: syntax error : ')'
johnsearch.cpp(7): error C2065: 'string' : undeclared identifier
johnsearch.cpp(7): error C2146: syntax error : missing ')' before identifier 'copied'
johnsearch.cpp(7): error C2374: 'sequentialSearch' : redefinition; multiple initialization
johnsearch.h(2) : see declaration of 'sequentialSearch'
johnsearch.cpp(7): error C2059: syntax error : ')'
johnsearch.cpp(8): error C2143: syntax error : missing ';' before '{'
johnsearch.cpp(8): error C2447: '{' : missing function header (old-style formal list?)
I'm obviously doing something completely and utterly wrong. I need JohnSearch.cpp for JohnSearch.h right? The forward declaration of the function in JohnSearch.h is defined in JohnSearch.cpp so I need those two files correct?
I'm just really confused. The example program we are supposed to modify has 2 .h files and 3 .cpp files. 2 of those .cpp files correspond with the 2 .h files so thats why I assumed I would also need 2 .h files and 3 .cpp files.
String is still undefined.
johnsearch.h(2): error C2065: 'string' : undeclared identifier
Your header file uses string , so you'll need to include <string>, before your declarations. You also need to qualify it as std::string since the string class resides in the std namespace
So your header file becomes:
#include <string>
const int NOT_FOUND = -1;
int sequentialSearch(std::string a[], std::string needle, int length );
(you should also use include guards in your header files)
Your JohnSearch.cpp also uses string, again, since string is in the std namespace, you'll get errors if you don't use std::string
In your TestSearch.cpp, you have a using namespace std; at the top, you could do the same in JohnSearch.cpp too, that way you can use string instead of std::string
When in doubt, simplify. You can boil the code down to something like this:
#include "JohnSearch.h"
void sequentialSearch(string needle)
{
}
and get the same error (and maybe a warning about an unused parameter).
Yes, string is a type of variable, but it's not innate in the C++ language itself, it's in one of the standard libraries, something you have to tell the compiler about:
#include "JohnSearch.h"
#include <string>
using std::string;
void sequentialSearch(string needle)
{
}
In your header file that you include, you need to have the exact same signature than your function in the cpp file.
Also dont forget to #include <string>, and then use a string like : std::string
E.g.
Int function(int number, int number2);
And in your cpp
Int function(int number, int number2)
{
// code
}
Signature is "int function(int, int)".

Random string from array

I cannot define a string array for unknown reasons on C++. I need to randomly get a string from this array.
Been trying the following:
string bands[] = { "Rammstein", "Slipknot", "Franz Ferdinand", "Gorillaz" };
I'm getting the following as error:
error C2146: syntax error : missing ';' before identifier 'bands'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C3845: 'SpurdoSparde::Form1::bands': only static data members can be initialized inside a ref class or value type
Just a reminder, I'm using a Windows forms applications. Not sure if it makes any difference whatsoever.
It seems you are not including string and/or not using std::string. The following works:
#include <string>
int main()
{
std::string bands[] = { "Rammstein", "Slipknot", "Franz Ferdinand", "Gorillaz" };
}
If you are after a dynamically sized collection of strings, you should prefer std::vector<std::string> over a C-style array. If you need fixed size, have a look at std::array<std::string, N> or tr1 or boost alternatives if you don't have C++11.
You either didn't include #include <string> or need to add the std:: namespace qualifier to your type:
std::string bands[] = { ... };
Prefer this over doing using namespace std;.
Also, you might should prefer to use a std::vector rather than a plain old C-style array:
std::vector<std::string> bands = { ... };

Compiling problems with wstring in c++

I need to refactor a .dll for a Zinc based Flash application.
After copy&paste a class from the master to the branch, I'm getting some strange compiling errors:
GameInfo.h(15): error C2146: syntax error : missing ';' before identifier 'm_wsVersion'
GameInfo.h(15): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
GameInfo.h(15): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
The addressed code:
// removed the comments
#include "stdafx.h"
#include <string.h>
class GameInfo {
public:
UINT m_uiGameId;
wstring m_wsVersion; // Line 15
UINT m_uiCheckSum;
wstring m_wsFilePath; // Same error report as on line 15
public:
static BOOL createFromFile(wstring path, GameInfo &target); // error "error C2061: syntax error : identifier 'wstring'" thrown
};
I use Visual Studio 2010 and in the IDE itself everything is okay, no syntactical errors or something like that. And as said I did not touch the code, headers seem fine.
Has anyone a clue what about this error?
Try using the string header, and qualifying the namespace:
#include <string>
class GameInfo {
....
std::wstring m_wsVersion;
};
#include <string> is the right standard include in C++ for string classes and use std::wstring.
I strongly recommend AGAINST using a using namespace std; inside one of your headers, as you would force anybody using the header to pull in the std stuff into the global namespace.

c++ weird struct and bitset error

I have this inside my private class declarations
#include "stdafx.h"
using namespace std;
template <typename Key, typename T>
class A{
//....
private:
static const unsigned int HSIZE = 32;
struct Bucket {
Key key;
T value;
bitset<HSIZE> jumpMap;
};
//....
};
Gives the following errors:
Error 1 error C4430: missing type specifier - int assumed
Error 2 error C2059: syntax error : '<'
Error 3 error C2238: unexpected token(s) preceding ';'
And when i remove the bitset line, it gives me no errors. What am i doing wrong?
EDIT: Added more relevant lines
Have you included the bitset header? I think you have missed it?
Should HMAX be HSIZE instead? Otherwise make sure you include < bitset >, and that the name is in scope. You probably have a using namespace std in your code, since you don't qualify it with std::. But my bet goes to HMAX <-> HSIZE.