Instead of putting my class in the same file as my main function, I'm trying to use a #include. Though, when I do this, I get an error for my constructor. This is my input.cpp file:
#ifndef input
#define input
using namespace std;
#include <string>
#include <iostream>
class input
{
public:
input(int sent)
{
s = sent;
}
void read();
void store(string s);
private:
int s;
};
#endif
This is my main function:
#include <iostream>
#include <string>
using namespace std;
#include "input.cpp"
int main()
{
cout<<"Hello, please enter your input"<<endl;
string sent;
getline(cin, sent);
cout<<sent;
input1 *newinput = new input1("hello");
system("pause");
return 0;
}
The error I'm getting is
"intelliSense expected a ';'"
in the body of my constructor. Though, when I copy / paste the class directly into my main.cpp file, the error goes away. Any idea on what is causing this?
Do no use using namespace in headers
You have input as macro constant and name of class is the same. I afraid it's the root your problem.
Prefer to use constructor initialization lists input(int sent) : s(sent) {}
UPDT
you may need constructor able to accept string as parameter input(const std::string& str1) : str(str1) {} where str is class member to handle string data.
You defined the constructor as having one parameter of type int
input(int sent)
{
s = sent;
}
but try to call it passing as an argument a string literal
input *newinput = new input("hello");
The string literal that has type const char[6] can not be implicitly converted to type int and the class has no other constructor that accepts character arrays as arguments.
EDIT: You changed you original post several times so it is not clear now whether using name input1 in stateent
input1 *newinput = new input1("hello");
is a typo or it is some other type.
Also you have a macro definition with the same name as the class name
#ifndef input
#define input
Change either the macro name or the class name.
Related
userInput.hpp
#include <string>
class UserInput{
public:
std::string rawInput;
std::string parseUserInput;
};
userInput.cpp
#include <iostream>
#include "userInput.hpp"
#include "stringManipulation.hpp"
using namespace std;
string branchCommand;
string parseUserInput(){
removeWhiteSpaces(rawInput);
return branchCommand;
}
I have created a class in userInput.hpp with the member function parseUserInput and I mean to define that function in userInput.cpp. However, when I try to use rawInput inside the definition, I cannot without making it so that rawInput is declared as static.
Is it possible to use the rawInput string in the function's definition which is in another file without making the rawInput variable static?
First of all, you've declared parseUserInput as a string field in your hpp, not as a function. Declare it as a member function by using paretheses.
std::string parseUserInput();
Second, in userInput.cpp you are defining a global function named parseUserInput(), not a member function. To define the member function on the UserInput class, use the scope resolution operator ::
std::string UserInput::parseUserInput() {
...
}
Finally, you should avoid using namespace std; in your code.
Your current class looks like this:
userInput.hpp
// Missing Header Guards Or #Pragma Once
#include <string>
class UserInput{
public:
std::string rawInput; // Member Variable of UserInput
std::string parseUserInput; // Member Variable of UserInput
};
userInput.cpp
#include <iostream> // Okay
#include "userInput.hpp" // Okay
#include "stringManipulation.hpp" // Okay
using namespace std; // Bad Practice
string branchCommand; // non const local Global Variable - can be bad practice
// Looks like a global function that is not a part of your class
string parseUserInput(){
removeWhiteSpaces(rawInput);
return branchCommand; // returning global variable that isn't used?
}
Did you mean?
userInput.hpp
#ifndef USER_INPUT_HPP
#define USER_INPUT_HPP
#include <string>
class UserInput {
public:
std::string rawInput; // Member Variable
std::string parseUserInput(); // Now a Member Function that Returns a std::string
};
#endif // USER_INPUT_HPP
userInput.cpp
#include <iostream>
#include "userInput.hpp"
#include "stringManipulation.hpp"
std::string branchCommand; // Still a bad idea if not const or static
std::string UserInput::parseUserInput( /* should this take a string from the user? */ ) {
removeWhiteSpaces( rawInput );
return branchCommand; // ? ... Still not sure what you are returning.
}
Hi have you thought about making a get function...
std::string returnRawInput() {return rawInput;}
you can then call this function to get the input...
I need to implement a class for one of my assignment and one of the function in the class that has string as datatype doesn't work
my definition code is :
#include <string>
class expression {
public:
expression();
void promptUser();
int getNum1();
int getNum2();
int calculate();
st::string str;
string numToString(int num);
string opToString();
private:
int num1;
int num2;
char op;
};
And in my implementation file
when I try to definite numTostring
string expression::numToString(int num) {
string digit;
...
It says that the declaration is incompatible with the header file(my class definition)
I have no idea why because both the function heading are the same.
the header file of expression.cpp( the implementation file) are :
#include "expression1.h"
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
Your class uses the unqualified name string, but there is no string data type defined in any enclosing scopes. There's a std::string data type defined in namespace std. That's looks to be the type that you need:
std::string str;
std::string numToString(int num);
std::string opToString();
You can keep from having to type out std:: everywhere by specifying a using statement:
using std::string;
But you might not want to do that inside a header file, so stick with fully qualifying the type.
If you want to use , you need to refer to it with std::
For example, your expression class declares:
st::string str;
string numToString(int num);
string opToString();
Which should be:
std::string str; // you typed st:: instead of std::
std::string numToString(int num); // lack of std::
std::string opToString(); // lack of std::
If you dont use 2 files (cpp + h) to define and declare your class then you can add line
using namespace std;
just after your includes. This way you wont have to type std:: each time you try to refer to string and similar types. However, using this is often called a bad "beginner" practice.
If you do use cpp+h then just add std:: before every string type and add using namespace std; to your cpp file.
If you want to know more then read:
1. http://www.cplusplus.com/doc/tutorial/namespaces/
2. Why is "using namespace std" considered bad practice?
3. How do you properly use namespaces in C++?
You also need to move
#include "stdafx.h"
up so it is the first header included. The compiler ignores everything that comes before that magic line.
I'm trying to implement a function that reads a column of data from a text file and stores it in a vector, which works. However when I try to implement it inside of a class I'm clearly missing some step. This causes the terminal to output the following message:
Outout for
error: member reference base type
'ifstream (string)' is not a structure or union
...
error: member reference base type
'ifstream (string)' is not a structure or union
while(!file.eof()){
..
error: invalid operands to binary
expression ('ifstream (*)(string)' and 'double')
file >> line;
In my class I try to implement the following function to be used with it's data members:
#include <iostream>
#include <vector>
#include <stdio.h>
#include <fstream>
using namespace std;
class spectData{
public:
vector<double> x, y, z;
vector< int> A;
vector<double> readVector(string){
ifstream file(string);
double line;
vector<double> a;
if(file.fail()){
cout << "-----------------\n";
cout << "Input file error!\n";
}
while(!file.eof()){
file >> line;
a.push_back(line);
}
return a;
};
};
Any hint as to why this wouldn't work inside a function, but would inside main function?
using namespace std;
...
vector<double> readVector(string){
// ~~~~~~^
// missing parameter name
ifstream file(string);
// ~~~~~^
// whoops, type name aka std::string instead of parameter name
What your ifstream file(string); currently does, it declares a function file that takes by value a parameter of the std::string type and returns the std::ifstream instance. Hence the error you get. What you probably meant to do is to supply a path parameter to your file's constructor:
vector<double> readVector(const string& path){
// ~~~~~~~~~~~~~~~~~^
// parameter name
ifstream file(path.c_str());
// ~~~^ ~~~~~~^
//
The issues in this code are numerous, including:
Failing to include <string>. Don't rely on another header to do that for you.
Invalid parameter naming (as in, you have none; remember parameters are Type name).
Building on the mistake from above, ifstream file(string); therefore declares a function called file that takes a string parameter and returns an ifstream (which is impossible, as that class does not support copy construction, but does support move construction, not that it matters here).
Using .eof() as a loop condition, which is nearly always wrong (and this is no exception). Read this for why.
Minor: Reinventing the iterative read operation. std::istream_iterator provides this functionality for you, and should be exploited.
Minor: blanketing this with using namespace std;
For example:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
class spectate
{
public:
std::vector<double> x, y, z;
std::vector< int> A;
std::vector<double> readVector(const std::string& fname)
{
std::vector<double> res;
std::ifstream file(fname);
if(!file)
{
std::cout << "-----------------\n";
std::cout << "Input file error!\n";
}
else
{ // dump the file of doubles into your vector
std::copy(std::istream_iterator<double>(file),
std::istream_iterator<double>(),
std::back_inserter(res));
}
return res;
}
};
Truth be told, you can forego much of that if error reporting is handled by the caller (such as an empty file, vector, etc), at which point that entire member can be reduced to simply:
std::vector<double> readVector(const std::string& fname)
{
std::ifstream file(fname);
return std::vector<double> {
std::istream_iterator<double>(file),
std::istream_iterator<double>() };
}
It somewhat brings into question whether the function is truly even needed at all. The caller could just as easily have done this entirely on their side.
string is a typename that you've pulled in inadvertently via the using namespace std. As a result, file is not what you intended - it is a function taking a std::string and returning an std::ifstream. Avoid using namespace std except in very controlled scopes - definitely not in header files.
#include <vector>
does includes std::string. After using namespace std; std::string becomes type string so you cant use string as variable name because it is a type.
You should write using std::vector; instead of using namespace std;
I am working on a project that asks the user to input a string, and then through get and set functions simply displays the string. However I am having issues actually having the user input the string and then pass those to the get and set functions. Here is my code:
This is my Main.cpp :
#include "stdafx.h"
#include <iostream>
#include "Laptop.h"
#include<string>
using namespace std;
int main()
{
Laptop Brand;
string i;
cout << "Enter your brand of laptop : ";
cin >> i;
Brand.setbrand (i);
return 0;
}
This is my Laptop.cpp :
#include "stdafx.h"
#include <iostream>
#include "Laptop.h"
#include <string>
using namespace std;
void Laptop::setbrand(string brand)
{
itsbrand = brand;
}
string Laptop::getbrand()
{
return itsbrand;
}
and this is my laptop.h :
#include<string>
class Laptop
{
private :
string itsbrand;
public :
void setbrand(string brand);
string getbrand();
};
In my laptop.cpp I have errors with setbrand and getbrand. They say that getbrand and setbrand are incompatible . I am pretty sure it has to do with I am passing a string through the parameters. Any ideas?
You have missed to include the correct namespace in the laptop.h file therefore the compiler cannot find any declared string class in the current (global) namespace. Just put, in the beginning of the file, using std::string;.
On a side note I'd avoid generic
using namespace std;
because it fights the purpose of having namespaces in the first place. It's usually better to specify exactly what kind of class you are using. Therefore:
using std::string;
is better.
The good fix here is to use std::string instead of string in the header file:
class Laptop
{
private :
std::string itsbrand;
public :
void setbrand(std::string brand);
std::string getbrand();
};
unlike the other files you do not have using namespace std. I would actually suggest just using std::string everywhere. It is safer and will save you from worse problems later on.
I have the following class definition, written in C++, residing in it's own header file (ManageFeed.h)
#include <string>
#include <fstream>
#include <iostream>
#include <cstring>
class ManageFeed
{
bool get_feed();
void format_feed();
bool refresh_feed();
int find_start_of_string(string tag, ifstream& rssfile);
public:
void display_feed_list();
void display_feed_item();
ManageFeed();
};
When I try to compile this code, I get the following error
custom-headers/ManageFeed.h:22: error: ‘string’ has not been declared
custom-headers/ManageFeed.h:22: error: ‘ifstream’ has not been declared
I find that I can successfully compile the code without any errors if I remove the parameters from the int find_start_of_string() function, but aren't the parameters required if data is to be passed into the function? If I try to call this function from main(), I receive the following error
reader.cpp:6: error: prototype for ‘void ManageFeed::find_start_of_string(std::string, std::ifstream&)’ does not match any in class ‘ManageFeed’
so they are clearly required for the function to be usable. The textbook I'm using has examples of class definitions in their own head files with parameters present, but there seems to be no other difference in the structure of my code, nor is there any explanation given for why the books code works and mine doesn't.
Question: Are the parameters not required in the definition (the function definitions in ManageFeed.cpp have parameters specified) or am I doing something wrong here?
If anybody's interested, here's my application file
#include "custom-headers/ManageFeed.h"
using namespace std;
ifstream rssfile;
const string tag;
void ManageFeed::find_start_of_string(string tag, ifstream& rssfile);
int main()
{
ManageFeed manage_example;
rssfile.open("rss.xml");
manage_example.find_start_of_string(tag, rssfile);
return 0;
}
and the implementation file for ManageFeed
#include "ManageFeed.h"
#include <iostream>
#include <string>
#include <cstring>
ManageFeed::ManageFeed()
{
}
/*
A function that will get the location of the RSS file from the user
*/
bool ManageFeed::get_feed()
{
cout << "Please specify the location of the feed: " << endl << endl;
cin >> feed_source;
return true;
}
void ManageFeed::store_feed()
{
ifstream source_feed;
source_feed.open(feed_source);
ifstream local_feed;
local_feed.open
(
"/../File System/Feed Source Files/Example Feed/Example Feed.xml"
);
local_feed << source_feed;
}
int ManageFeed::find_start_of_string(string tag, ifstream& rssfile)
{
bool return_value = false;
string line;
size_t found;
do
{
getline(rssfile, line, '\n');
found = line.find(tag);
if (found != string::npos)
{
return_value = true;
return found;
}
} while (!return_value && !rssfile.eof());
if (!return_value)
{
}
}
John has the right solution. Here is the reasoning.
Both string and ifstream live in a namespace called std. When you say string you are telling the compiler to look into the global namespace and find a token called string. There is no such thing. You have to tell the compiler where to find string.
To do so you can either prefix them with std::string and std::ifstream or you can add using namesapce std; at the top of your header file.
Looking a little more closely, you do have the using directive in you .cpp file, but you put it after you include the header. That means the compiler parses the header without the namespace and then parses the rest of the file with it. If you just move the using directive above the header include, it will also fix your problem. Note, however, that anything else using the header will also need to do that same. Thus, start your .cpp file this way:
using namespace std;
#include "custom-headers/ManageFeed.h"
Change:
int find_start_of_string(string tag, ifstream& rssfile);
to:
int find_start_of_string(std::string tag, std::ifstream& rssfile);
Aside: why were there so many questions just like this one today?