Passing by reference character arrays - arrays

I'm attempting to pass a character array located in _name into a char reference called name.
However, when passing the array pointer into the reference, it would ONLY display the first character rather than the whole string.
My question is how would you create a Character reference array to copy the original pointer into it then displaying it? As show in item.cpp we copy _name pointer into reference of name then return name, it however only displays the first character of the string.
I will only show the relevant pieces of my code.
Item.cpp:
void Item::name(const char * name){
strncpy(_name, name , 20);
}
const char& Item::name() const{
char& name = *_name;
return name;
}
ItemTester.cpp:
Main():
int main(){
double res, val = 0.0;
fstream F;
SItem Empty;
SItem A("456", "AItem", 200);
SItem B("567", "BItem", 300, false);
//cout << A.name() << endl;
B.quantity(50);
//cout << Empty << endl;
cout << A << endl << B << endl << endl;
cout << "Enter Item info for A: (Enter 123 for sku)" << endl;
cin >> A;
cout << "Copying A in C ----" << endl;
SItem C = A;
cout << C << endl << endl;
cout << "Saving A---------" << endl;
A.save(F);
cout << "Loading B----------" << endl;
B.load(F);
cout << "A: ----------" << endl;
cout << A << endl << endl;
cout << "B: ----------" << endl;
cout << B << endl << endl;
cout << "C=B; op=----------" << endl;
C = B;
cout << C << endl << endl;;
cout << "Operator ==----------" << endl;
cout << "op== is " << ((A == "123") && !(A == "234") ? "OK" : "NOT OK") << endl << endl;
cout << "op+=: A += 20----------" << endl;
A += 20;
cout << A << endl << endl;
cout << "op-=: A -= 10----------" << endl;
A -= 10;
cout << A << endl << endl;
cout << "op+=double: ----------" << endl;
res = val += A;
cout << res << "=" << val << endl << endl;
return 0;
}
ostream write
virtual std::ostream& write(std::ostream& os, bool linear)const{
return os << sku() << ": " << name() << endl
<< "Qty: " << quantity() << endl
<< "Cost (price * tax): " << fixed << setprecision(2) << cost();
}
Let me know if i missed any important details and il edit my post with it.

char& is reference to char, thus just a single character. Reference to array of characters would be char*&.
Example:
class Test
{
private:
static const size_t maxlen = 100;
char* _name;
public:
Test() : _name(new char[maxlen+1]) {}
~Test() {delete _name;}
void name(const char* s)
{
if(strlen(s) >= maxlen)
throw "too long";
else
{
memcpy(_name, s, strlen(s) * sizeof(char));
_name[strlen(s)] = '\0';
}
}
char*& name()
{
return _name;
}
};
int main()
{
Test obj;
obj.name("testname");
cout<<"Name = "<<obj.name()<<endl;
obj.name()[0] = '*';
cout<<"After change: Name = "<<obj.name()<<endl;
return 0;
}
EDIT:
I would change "getter" to something like:
char*& Item::name() {
return _name;
}
Actually if you do want the method to be "const", in the sense that user of the class should not change the elements of the array, or the actual address of the array, then you need not return a char*&, you can simply return const char*
const char* Item::name() const {
return _name;
}
As far as I see, the purpose of a char*& type is that the client would be able to change the actual address of an address.

As CForPhone pointed out, char& is not really what you want, you probably meant char*. But even then, using char* to represent strings is for C. In C++, you should use std::string:
const string Item::name() const{
string name(_name);
return name;
}

Related

how the use of cin.ignore and getline should be

#include <iostream>
using namespace std;
int main () {
int pemboking, kode_lap[8], durasi[8];
string nama[8], tanggal[8], jam[8];
cout << "\nMasukan jumlah pembooking : ";
cin >> pemboking;
cout << endl;
for (int i = 0; i < pemboking; i++) {
cout << "Transaksi ke " << i + 1 << endl;
cout << "Masukan Nama : ";
getline(cin, nama[i]);
cout << "Masukan Kode Lapangan : ";
cin >> kode_lap[i];
cout << "Masukan Tanggal Sewa : ";
cin >> tanggal[i];
cout << "Masukan Jam main : ";
getline(cin, jam[i]);
cout << "Masukan Durasi Jam Main : ";
cin >> durasi[i];
cout << endl;
cout << endl;
}
}
when I use cin.ignore, the error will go directly to the input with index 1, index 0 is missed. if you don't use cin ignore it just skips the input using getline.
so how should i use the code, for a space input from the user.
although not in the same way, I hope the code meets my expectation that it can ask the user to input spaces for string type

if loop inside a void function not working

So I'm doing a program for a class, and I set up an if loop inside a function definition to set parameters for entries. I'm supposed to be taking inputs between 0 and 10 only. But it's only catching the numbers that are less than 0. It won't catch the numbers larger than 10.
int main()
{
float score1, score2, score3, score4, score5;
cout << endl;
cout << "Judge #1: " << endl;
getJudgeData(score1);
cout << "Judge #2: " << endl;
getJudgeData(score2);
cout << "Judge #3: " << endl;
getJudgeData(score3);
cout << "Score #4: " << endl;
getJudgeData(score4);
cout << "Score #5: " << endl;
getJudgeData(score5);
calcScore(score1, score2, score3, score4, score5);
return 0;
}
void getJudgeData (float &score)
{
cin >> score;
if(score < 0 || score > 10)
{
cout << "Error: Please enter a score between 0 and 10." << endl;
cin >> score;
}
}
Please change the if condition in your getJudgeData function into a while loop:
void getJudgeData (float &score)
{
cin >> score;
while (score < 0 || score > 10)
{
cout << "Error: Please enter a score between 0 and 10." << endl;
cin >> score;
}
}
Otherwise the condition will be only checked once, means for the first input of every judge. This isn't intended, if I understood your issue correctly.
Please find more information regarding the while loop here:
while

check order of array in c, using recursion and malloc [duplicate]

I am trying to debug a recursive function used to validate user input and return a value when the input is OK. The function looks like this:
double load_price()
{
double price;
Goods * tempGd = new Goods();
cin >> price;
while (!cin)
{
cin.clear();
#undef max
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "You didn't enter a number. Do so, please: ";
cin >> price;
} // endwhile
if (!tempGd->set_price(price))
{
cout << endl;
cout << "The price " << red << "must not" << white << " be negative." << endl;
cout << "Please, insert a new price: ";
load_price();
}
else
{
delete tempGd;
return price;
}
}
The method set_price() of Goods class looks as follows
bool Goods::set_price(double price)
{
if (price> 0)
{
priceSingle_ = price;
priceTotal_ = price* amount_;
return true;
}
return false;
}
I tried drawing the problem on a paper but all my diagrams seem to look the way my function already looks like. I think there are some problems with returns, but I do not know where.
Help would be greatly appreciated.
You're not using the return value of the recursive call. You need to do:
return load_price();
Who talked you into using recursion for that problem?
#undef max
double load_price()
{
for(;;) {
double price;
cin >> price;
if (!cin)
{
cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "You didn't enter a number. Do so, please: ";
continue;
}
if (!Goods().set_price(price))
{
cout << endl;
cout << "The price " << red << "must not" << white << " be negative." << endl;
cout << "Please, insert a new price: ";
continue;
}
return price;
}
}

Pointer to char outputs differently compared to other primitives?

I have this code that produces an unexpected result for a char pointer:
#include <iostream>
#include <stdlib.h>
#include <string>
void main(int argv, char* argc[]) {
char* test1 = new char[7];
test1[0] = 'H';
test1[1] = 'a';
test1[2] = 'l';
test1[3] = 'e';
test1[4] = 't';
test1[5] = 'y';
test1[6] = 'a';
char* t2 = &test1[3];
std::cout << *t2 << std::endl;
std::cout << t2 << std::endl;
std::cout << std::endl;
int v[] = { 1,2,3,4 };
int* v2 = &v[0];
std::cout << *v2 << std::endl;
std::cout << v2 << std::endl;
std::cout << std::endl;
float f[] = { 0.2, 0.4, 0.6 };
float* f2 = &f[1];
std::cout << *f2 << std::endl;
std::cout << f2 << std::endl;
std::cout << std::endl;
std::string str = "A_string";
std::string *str2 = &str;
std::cout << *str2 << std::endl;
std::cout << str2 << std::endl;
std::cout << std::endl;
std::cin.ignore();
}
The output for this is variable but usually something like this:
What's going on? For the int, float, and string, printing the address prints the pointer address and printing the pointer prints the correct value. However, for the char array, while printing the pointer also prints the correct value, printing the address prints the last 4 elements of the array and a bunch of crap that varies per run.
Is there something about char that causes this or do I just have a funky setup? I've tried initializing the char array with brackets but it's the same result.
Never mind. I guess the solution is this:
std::cout << *t2 << std::endl;
std::cout << (void*)t2 << std::endl;
std::cout << std::endl;
Also found:
Why is address of char data not displayed?

How can I translate this C++ function to C?

The code below is in C++. How do I translate it to C?
void drawBoard()
{
system( "cls" );
cout << "SCORE: " << score << endl << endl;
for( int y = 0; y < 4; y++ )
{
cout << "+------+------+------+------+" << endl << "| ";
for( int x = 0; x < 4; x++ )
{
if( !board[x][y].val ) cout << setw( 4 ) << " ";
else cout << setw( 4 ) << board[x][y].val;
cout << " | ";
}
cout << endl;
}
cout << "+------+------+------+------+" << endl << endl;
}
The code is pretty much C compatible already. However, the couts are a C++ construct.
To make it fully C compatible, you could replace cout with printf. For instance, in your code,
cout << "SCORE: " << score << endl << endl; --> printf("SCORE: %d \n\n", score);
You'll have to play around with the different parameters to get the formatting and output right, but that's the general idea. A good reference is this site: Printf
Assuming val and score are int, the following lines:
cout << "SCORE: " << score << endl << endl;
cout << "+------+------+------+------+" << endl << "| ";
cout << setw( 4 ) << " ";
cout << setw( 4 ) << board[x][y].val;
would translate to:
printf("SCORE: %d\n\n", score);
printf("+------+------+------+------+\n| ";
printf(" ");
printf("%4d", board[x][y].val);
You can figure out the rest .

Resources