anyone know how to initialize an empty array - c++

Anyone know how to Initialise the array of car registration structures by placing a “Empty” in the car registration number of each array element.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
struct car;
{
string car_reg = 0;
char car_manuf[30];
char car_model[30];
double price;
string car_reg{};
}
}
need some h3elp

Explanation inline.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
struct car // removed ; the ; terminates the definition, cutting it off
// and leaving you with a declaration. Everything in the braces
// that follow would be seen as a block of code defining two
// automatic variables scoped inside the block. Useless in this
// case.
{
string car_reg = 0; // this is actually NASTY! More on it later
char car_manuf[30] = "EMPTY"; // assigns default value. But only if your
// compiler comes from this decade.
// If you are rocking an antique you can't
// do this. Will cover what you can do below.
char car_model[30] = "EMPTY";
string car_reg{}; // cannot reuse the car_reg identifier in the same scope
// car_reg is either a variable or a function.
}; // ; goes here
car c; // for testing purposes
cout << c.car_manuf << ',' << c.car_model; // for testing
}
string car_reg = 0; is nasty. What it does is defines a member variable car_reg and uses 0 as the default. The 0 is converted to a null pointer to a char array. The string constructor attempts to initialize from a null pointer and blows up at runtime. The compiler is just fine with this bit of stupidity because in the old days NULL could be #define NULL 0 and we don't want to break decades of old code by fixing this problem.
Since we can't do default initializations in pre C++11 code we need a constructor to do the work. Yup. structs can have constructors. This is because a struct and a class are almost identical. The only difference you're ever likely to see between the two is class defaults to private access and structs default to public access.
struct car
{
char car_manuf[30];
char car_model[30];
car (): car_manuf("EMPTY"), car_model("EMPTY")
{
}
};
Note that his isn't as groovy as it looks. You're usually better off with something like
struct car
{
string car_manuf;
string car_model;
car (const string & manuf,
const string & model): car_manuf(manuf), car_model(model)
{
}
};
and not allowing the empty case at all. When possible force users to initialize a class into a fully initialized state. And use std::string. Very handy tool, std::string.
Note that
struct car
{
char car_manuf[30];
char car_model[30];
car (const char * manuf,
const char * model):
car_manuf(manuf), car_model(model) // fails to compile
{
}
};
is not possible. You can't initialize a char array with a pointer to char. I'm not entirely certain why the language doesn't have a rule to handle this, but it doesn't. If forced to use char arrays,
struct car
{
char car_manuf[30];
char car_model[30];
car (const char * manuf,
const char * model)
{
strcpy(car_manuf, manuf);
strcpy(car_model, model);
}
};
and make dang sure that manuf and model will fit in 29 characters or less.

Have you tried a simple for loop, to fill (for example) the char_model array with zeros?
....
char car_model[30];
/* Adding the for loop here (it will fill car_model's elements with zeros*/
for(int i=0; i<=sizeof(car_model); i++){
car_model[i]=0;
....

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
struct car
{
string car_reg = {"Empty"};
char car_manuf[30];
char car_model[30];
car(const char* manuf,
const char* model)
{
strcpy(car_manuf, manuf);
strcpy(car_model, model);
}
};
}

Related

Printing the first value from more than one vector in C++

I am trying to print the first value from each vector shown below in the main function.
#include <iomanip>
#include <map>
using namespace std;
typedef unsigned int vect;
int main() {
std::vector<vect> p;
vector<vect> a = { 4,2,3,1 };
vector<vect> b = { 4,2,3,1 };
vector<vect> c = { 4,2,3,1 };
vector<vect> d = { 4,2,3,1 };
int i;
for (i=0; i<a.size(); i++)
cout << a[i];
}
Function first_preference() from my function.cpp shown below
#include "function.h"
#include <string>
#include <iostream>
using namespace std;
person test::first_preference() const {
const person& first = p.front();
return first; //current first pref
}
The function is declared in this header class
#ifndef FUNCTION_H
#define FUCNTION_H
#include <vector>
typedef unsigned int person;
typedef unsigned int vect;
std::vector<vect> p;
class test {
public:
person first_preference() const;
};
#endif
I want the function first_preference() to be called from main() where the function should print the first value of each vector, how would I go about this?
I want the function first_preference() to be called from main() where the function should print the first value of each vector
Some issues:
You have a global std::vector<vect> p in your header file (which is not a good idea to begin with) which is shadowed by std::vector<vect> p in main. What you put in the p in main will not be accessible from instances of test. Those instances only knows about the global p.
You don't #include "function.h" in main.cpp so you can't create test objects in main.
If you #include "function.h" in main.cpp there's no need to typedef unsigned int vect; since you did that in function.h already. It's not an error, but confusing and unnecessary.
The vector<vect> instances a, b, c and d have no connection with test or any of the ps whatsoever so what you put in those vectors can't possibly be printed by instances of test unless you pass them on to test somehow.
You declare vectors of vect but first_preference() returns a person by value. vect and person happen to be aliases of the same fundamental type, but it seems like there is something wrong with this interface.
In main.cpp you don't instantiate a test, you iterate over a and first_preference() is never called so there's no hope for it to be used.
Why is “using namespace std;” considered bad practice?

Why is my setter method producing a bad access error

Bad access means that i am trying to access memory that doesn't exists I have tried and tried to allocate memory for this class, but have failed everywhere. I do not know where the error is actual coming from. It only tells me that my setter method is when the program crashes. In the setFName() method is where the error occurs. But in the main method is where it actually occurrs.
nurse.hpp
#ifndef Nurse_hpp
#define Nurse_hpp
#include <stdio.h>
#include <string>
#include <stdlib.h>
using namespace std;
class nurse{
private:
string firstName;
public:
nurse() {
firstName = "jim";
}
string getFName() {return firstName;}
void setFName(string fName) {firstName = fName;} // Thread 1: bad access 0x0
};
#endif /* Nurse_hpp */
here is where the error is actually happening
main.cpp
#include <cstdint> // ::std::uint64_t type
#include <cstddef> // ::std::size_t type
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include "nurseHolder.hpp"
using namespace std;
nurseHolder *l = new nurseHolder();
int main() {
return 0;
}
and finally here is the class that is causing the issue
nurseHolder.hpp
#ifndef Nurses_hpp
#define Nurses_hpp
#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include "Nurse.cpp"
using namespace std;
class nurseHolder{
private:
int nurse_cnt;
int nurse_cap;
vector<nurse> nurse_list;
public:
nurseHolder() {
nurse_cnt = 0;
nurse_cap = 10;
for(int i= 0; i < 11; i++){
nurse_list[i].setFName("na");
}
}
vector<nurse> &getNurseList() { return nurse_list;}
};
#endif /* Nurses_hpp */
I tried to make this compact as possible sorry if its a lot of code.
here is what I changed to make the code work:
nurseHolder() {
nurse_cnt = 0;
nurse_cap = 10;
for(int i= 0; i < 11; i++){
nurse l;
nurse_list.pushback(l);
}
}
Is this a correct way to do this?
Your vector nurse_list has size 0. So you cannot use [] operator to set names.
There are two ways you can correct this:
Set an initial size to the vector and use [] to set names.
Use push_back to add elements to the vector.
First method.
nurse_list.resize(noOfTotalNurses).
nurse_list[i].setFName("name");
Second method.
nurse tNurse; //local nurse object
tNurse.setFName("name");
nurse_list.push_back(tNurse);

Deconstruct const pointer?

It's probably very basic but I am stuck and simply don't know what the problem is.
The main code is predefined as a task. The goal is to use const as much as possible. The following constructor is just supposed to copy the literal string to the const m_data and that works fine but I am not able to free the memory - it always leaves 1 block. What am I missing?
main.cpp
#include <iostream>
#include "immstring.hpp"
using namespace std;
using namespace Util;
int main()
{
const ImmutableString s1("Hello");
}
immu.hpp
#include <cstring>
namespace Util {
class ImmutableString {
public:
ImmutableString(const char* src);
~ImmutableString();
private:
char* const m_data;
};
}
immu.cpp
#include "immstring.hpp"
#include <iostream>
#include <cstring>
namespace Util
{
ImmutableString::ImmutableString(const char* src)
:m_data{strcpy(new char[strlen(src)+1],src)}{}
ImmutableString::~ImmutableString()
{
delete m_data;
}
}
To leave all array memories blocks you have to use delete like this :
delete[] m_data;
Thanks,
Robin.

Objects not storing/retrieving correctly in vector (C++)

I'm a complete c++ beginner.
I'm trying to do a couple things that seem pretty basic: Create an object of a certain class, store it in a vector, then output a value of that object. At the moment it outputs a rectangle character, no matter what character I store.
Here's the code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <conio.h>
#include <time.h>
#include <windows.h>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
class terrainType
{
public:
string name;
char symbol;
int freq;
terrainType(string,char,int);
};
terrainType::terrainType(string name, char symbol, int freq)
{
name=name;
symbol=symbol;
freq=freq;
}
int main()
{
vector<terrainType> terrainTypes;
terrainType dirt("dirt",'.',1);
terrainTypes.push_back(dirt);
cout << terrainTypes[0].symbol;
return 0;
}
Any advice or background info is appreciated. Thanks!
The three assignments you have in the constructor are effectively no-ops (you're assigning each variable to itself):
terrainType::terrainType(string name, char symbol, int freq)
{
name=name;
symbol=symbol;
freq=freq;
}
The issue is that you have two things called name, and you expect the compiler to figure out that in name=name the left-hand side refers to one of them, whereas the right-hand side refers to the other.
The cleanest way to fix this is by changing to constructor like so:
terrainType::terrainType(string name, char symbol, int freq)
: name(name),
symbol(symbol),
freq(freq)
{
}
The rules of the language are such that this would have the intended meaning.
Another alternative is to avoid using the same identifier to refer to both a member and a function argument:
terrainType::terrainType(string name_, char symbol_, int freq_)
{
name=name_;
symbol=symbol_;
freq=freq_;
}
Yet another alternative is to prefix member access with this->:
terrainType::terrainType(string name, char symbol, int freq)
{
this->name=name;
this->symbol=symbol;
this->freq=freq;
}

passing struct parameter by reference c++

how can i pass a struct parameter by reference c++, please see below the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
struct TEST
{
char arr[20];
int var;
};
void foo(char * arr){
arr = "baby"; /* here need to set the test.char = "baby" */
}
int main () {
TEST test;
/* here need to pass specific struct parameters, not the entire struct */
foo(test.arr);
cout << test.arr <<endl;
}
The desired output should be baby.
I would use std::string instead of c arrays in c++
So the code would look like this;
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
using namespace std;
struct TEST
{
std::string arr;
int var;
};
void foo(std::string& str){
str = "baby"; /* here need to set the test.char = "baby" */
}
int main () {
TEST test;
/* here need to pass specific struct parameters, not the entire struct */
foo(test.arr);
cout << test.arr <<endl;
}
That's not how you want to assign to arr.
It's a character buffer, so you should copy characters to it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
struct TEST
{
char arr[20];
int var;
};
void foo(char * arr){
strncpy(arr, "Goodbye,", 8);
}
int main ()
{
TEST test;
strcpy(test.arr, "Hello, world");
cout << "before: " << test.arr << endl;
foo(test.arr);
cout << "after: " << test.arr << endl;
}
http://codepad.org/2Sswt55g
It looks like you are using C-strings. In C++, you should probably look into using std::string. In any case, this example is passed a char array. So in order to set baby, you will need to do it one character at a time (don't forget \0 at the end for C-strings) or look into strncpy().
So rather than arr = "baby" try strncpy(arr, "baby", strlen("baby"))
It won't work for you beause of the reasons above, but you can pass as reference by adding a & to the right of the type. Even if we correct him at least we should answer the question. And it wont work for you because arrays are implicitly converted into pointers, but they are r-value, and cannot be converted into reference.
void foo(char * & arr);