Hi just getting into coding, can someone create or show me a code that covers basics so i can have reference to look back on. I would much appreciate the help.
Thank you.
Looking for something that includes stuff like:
constructors - default and/or parameterized, copy
reading from a file
destructor
accessors and/or mutators functions
Inherited class
etc
Thanks
// Default Constructor and Custom Constructor
// Default constructor is any constructor that takes
// no parameters. (It is created by default unless another is defined.
// in which case you would have to define a default constructor yourself.)
#include <iostream>
#include <string>
class MyClass
{
public:
MyClass() // Default constructor
{
std::cout << "Default constructor called!\n";
Text = "Hello, world!\n"; // Default string
std::cout << Text << '\n';
}
MyClass(std::string text) // Custom constructor
{
std::cout << "Custom constructor called!\n";
Text = text; // Custom string! :)
std::cout << Text << '\n';
}
private:
std::string Text;
}; // <--- semi-colon is needed at end of class!
int main()
{
MyClass obj; // Calls MyClass().
MyClass obj2("Hello!!"); // Calls MyClass(std::string) (Custom constructor)
}
#include <iostream>
#include <string>
#include <fstream>
bool isPrefix(std::string str, std::string prefix) // Test if one string is the first part of another
{
return (str.compare(0, prefix.size(), prefix) == 0);
}
// Reads each line from a file, if a line starts with
// the parameter passed in (prefix) it returns that line!
std::string SearchForInFile(std::ifstream& stream, std::string prefix)
{
std::string data;
while(std::getline(stream, data))
{
if(isPrefix(data, prefix))
{
return data.substr(prefix.size()); // substr(): removes a certain number of
// characters from the beggining of a string.
}
}
return"\0";
}
int main()
{
std::ifstream stream("file.txt"); // File to read from (input file stream)
std::cout << SearchForInFile(stream, "Text::");
}
Now, that code reads this file:
# file.txt
IgnoreThisLine::Hello, world!
Text::This will be printed to console!
AnotherIgnoredLine::Test!
Random Giberish