how the use of cin.ignore and getline should be - arrays

#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

Related

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;
}
}

How do I input more than one dynamic array integer?

How would I modify this code so that I can enter in more than just one coefficient?
I am suppose to be able to enter in something like "3 2 1" and the spaces shouldn't affect my user input but I'm not sure how to do this.
This is the code I have so far:
#include <iostream>
using namespace std;
int *foil(int A[], int B[], int co, int coo)
{
int *product = new int[co+coo-1];
for (int i = 0; i<co+coo-1; i++)
product[i] = 0;
for (int i=0; i<coo; i++)
{
for (int j=0; j<co; j++)
product[i+j] += A[i]*B[j];
}
return product;
}
void printPoly(int poly[], int co)
{
for (int i=0; i<co; i++)
{
cout << poly[i];
if (i != 0)
cout << "x^" << i ;
if (i != co-1)
cout << " + ";
}
}
int main()
{
int co, coo;
int *A;
A=new int[co];
int *B;
B=new int[coo];
cout << "How many coefficients are in the first poly?: ";
cin >> co;
cout << "What are the coefficients? (Lowest power first): ";
cin >> *A;
cout << "How many coefficients are in the second poly?: ";
cin >>coo;
cout << "What are the coefficients? (Lowest power first): ";
cin >>*B;
printPoly(A, coo);
cout << "\n";
cout << "times" << endl;
printPoly(B, co);
cout << "\n";
cout << "-----" << endl;
int *product = foil(A, B, co, coo);
printPoly(product, co+coo-1);
return 0;
}
It outputs this:
How many coefficients are in the first poly?: 3
What are the coefficients? (Lowest power first): 3 2 1
How many coefficients are in the second poly?: What are the coefficients? (Lowest power first): 3 + 0x^1
times
1 + 0x1 + 0x^2
-----
3 + 0x^1 + 0x^2 + 0x^3
I want it to output it like this:
How many coefficients are in the first poly?: 3
What are the coefficients? (Lowest power first): 3 2 1
How many coefficients are in the second poly? 3
What are the coefficients? (Lowest power first): 1 2 1
3 + 2x^1 + 1x^2 
times 
1 + 2x^1 + 1x^2 
-----­­­­­ 
3 + 8x^1 + 8x^2 + 4x^3 + 1x^4
you need to take the inputs in a loop.
here is how you can do it.
cout << "How many coefficients are in the first poly?: ";
cin >> co;
cout << "What are the coefficients? (Lowest power first): ";
for(int i=0;i<co;i++)
cin >> *(A+i);
cout << "How many coefficients are in the second poly?: ";
cin >>coo;
cout << "What are the coefficients? (Lowest power first): ";
for(int i=0;i<coo;i++)
cin >>*(B+i);
printPoly(A, coo);
cout << "\n";
cout << "times" << endl;
printPoly(B, co);
cout << "\n";
cout << "-----" << endl;
int *product = foil(A, B, co, coo);
printPoly(product, co+coo-1);
getch();
return 0;
Here is the output image

Passing by reference character 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;
}

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