QString::number pad with zero if number is positive - string-formatting

I'm trying to print out numbers with fixed alignment such that if the number is positive OR negative it will still be aligned. Basically if the number is negative nothing gets padded, but if the number is positive then it gets a single padding in the place of where the '+' symbol would go
Here's some code that explains my problem:
qDebug() << "current behaviour";
qDebug() << "Num:" << QString::number(-5);
qDebug() << "Num:" << QString::number(5);
qDebug() << "desired behaviour";
qDebug() << "Num:" << QString("-5");
qDebug() << "Num:" << QString(" 5");
qDebug() << "this works, but would like to avoid this much typing...";
int val = -5;
qDebug() << "Num:" << QString(val >= 0, ' ') + QString::number(val);
val = 5;
qDebug() << "Num:" << QString(val >= 0, ' ') + QString::number(val);
And here's the output:
I know QString::number() has a number of parameters to adjust precision, but I haven't been able to find the right parameters to do this easily.
EDIT
My original example was a poor one. So here is more information. The values will actually be of type double and I know their values will always be -10 < val < 10. I also only want to display one decimal place. So here's a more realistic example (also using QString::arg() this time)
qDebug() << "current output";
qDebug() << "num:" << QString("%1").arg( 5.532,4,'f',1,QChar('0'));
qDebug() << "num:" << QString("%1").arg(-5.532,4,'f',1,QChar('0'));
qDebug() << "num:" << QString("%1").arg( 0.532,4,'f',1,QChar('0'));
qDebug() << "num:" << QString("%1").arg(-0.532,4,'f',1,QChar('0'));
qDebug() << "desired output";
qDebug() << "num:" << QString(" 5.5");
qDebug() << "num:" << QString("-5.5");
qDebug() << "num:" << QString(" 0.5");
qDebug() << "num:" << QString("-0.5");
And here's the output:

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

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 .

2 bytes represent 3 integers in C

I have two bytes, 8 bit octets, which should be read as: [3 bits][4 bits][3 bits].
Example:
unsigned char octet1 = 0b11111111; // binary values
unsigned char octet2 = 0b00000011;
As integers: [7][15][7].
Anybody can give me a hint where to start?
In a kind of pseudocode
octet1 = 0b11111111
octet2 = 0b00000011
word = octet1 | octet2<<8
n1 = word & 0b111
n2 = word>>3 & 0b1111
n3 = word>>7 & 0b111
Hi here is a method that is tested and compiled using VC++9
#pragma pack( 1 )
union
{
struct
{
unsigned short val1:3;
unsigned short val2:4;
unsigned short val3:3;
unsigned short val4:6;
} vals;
struct
{
unsigned char octet1:8;
unsigned char octet2:8;
} octets;
short oneVal;
} u = {0xFFFF};
unsigned char octet1 = 0xFF; //1 1111 111
unsigned char octet2 = 0x03; //000000 11
//000000 111 1111 111 0 7 15 7
u.octets.octet1 = octet1;
u.octets.octet2 = octet2;
cout << "size of u.vals:" << sizeof(u.vals)<< endl;
cout << "size of u.octets:" << sizeof(u.octets)<< endl;
cout << "size of u.oneVal:" << sizeof(u.oneVal)<< endl;
cout << "size of u:" << sizeof(u)<< endl;
cout << endl;
cout << "Your values:" << endl;
cout << "oneVal in Hex: 0x";
cout.fill( '0' );
cout.width( 4 );
cout<< hex << uppercase << u.oneVal << endl;
cout << "val1: " << (int)u.vals.val1 << endl;
cout << "val2: " << (int)u.vals.val2 << endl;
cout << "val3: " << (int)u.vals.val3 << endl;
cout << "val4: " << (int)u.vals.val4 << endl;
cout << endl;
octet1 = 0xCC; //1 1001 100
octet2 = 0xFA; //111110 10
//111110 101 1001 100 62 5 9 4
u.octets.octet1 = octet1;
u.octets.octet2 = octet2;
cout << "Some other values:" << endl;
cout << "oneVal in Hex: 0x";
cout.fill( '0' );
cout.width( 4 );
cout<< hex << uppercase << u.oneVal << endl;
cout << dec;
cout << "val1: " << (int)u.vals.val1 << endl;
cout << "val2: " << (int)u.vals.val2 << endl;
cout << "val3: " << (int)u.vals.val3 << endl;
cout << "val4: " << (int)u.vals.val4 << endl;
cout << endl;
octet1 = 0xCC; //1 1001 100
octet2 = 0xFA; //111110 10
//111110 101 1001 100 62 5 9 4
u.oneVal = ( (( unsigned short )octet2 ) << 8 ) | ( unsigned short )octet1;
cout << "Some thing diffrent asignment:" << endl;
cout << "oneVal in Hex: 0x";
cout.fill( '0' );
cout.width( 4 );
cout<< hex << uppercase << u.oneVal << endl;
cout << dec;
cout << "val1: " << (int)u.vals.val1 << endl;
cout << "val2: " << (int)u.vals.val2 << endl;
cout << "val3: " << (int)u.vals.val3 << endl;
cout << "val4: " << (int)u.vals.val4 << endl;
cout << endl;
Also note that I uses #pragma pack( 1 ) to set the structure packing to 1 byte.
I also included a way of assigning the two octets into the one short value. Did this using bitwise shift "<<" and bitwise or "|"
You can simplify the access to u by dropping the named structures. But I wanted to show the sizes that is used for the structures.
Like this:
union
{
struct
{
unsigned short val1:3;
unsigned short val2:4;
unsigned short val3:3;
unsigned short val4:6;
};
struct
{
unsigned char octet1:8;
unsigned char octet2:8;
};
short oneVal;
} u = {0xFFFF};
Access would now be as simple as
u.oneVal = 0xFACC;
or
u.octet1 = 0xCC;
u.octet2 = 0xFA;
you can also drop either oneVal or octet1 and octet2 depending on what access method you like.
No need to put the two bytes together before extracting bits we want.
#include <stdio.h>
main()
{
unsigned char octet1 = 0b11111111;
unsigned char octet2 = 0b00000011;
unsigned char n1 = octet1 & 0b111;
unsigned char n2 = (octet1 >> 3) & 0b1111;
unsigned char n3 = (octet1 >> 7) | (octet2 + octet2);
printf("octet1=%u octet2=%u n1=%u n2=%u n3=%u\n",
octet1, octet2, n1, n2, n3);
}
oct2| oct1
000011|1 1111 111
---- ---- ---
7 0xf 7
Just a hint,(assuming it is homework)
Note: 0x11111111 doesn't mean 8 bits all set to 1. It's an hexadecimal number of 4 bytes, where any byte is set to 0x11.
0xFF is a single byte (8 bit) where any bit is set to 1.
Then, to achieve what you want you could use some MACROs to isolate the bits you need:
#define TOKEN1(x) ((x)>>7)
#define TOKEN2(x) ( ((x)>>3) & (0xFF>>5) )
#define TOKEN3(x) ( ((x)>>5) & (0xFF>>5) )
Didn't test it.
Another idea, could be that of putting in an union a char and a struct using bitfield chars
union {
struct { char a:3; char b:4; char c:3; };
char x;
};
This way you can use x to edit the whole octet, and a, b and c to access to the single tokens...
Edit: 3+4+3 != 8.
If you need 10 bits you should use a short instead of a char. If, instead, some of those bits are overlapping, the solution using MACRO will probably be easier: you'll need more than one struct inside the union to achieve the same result with the second solution...
You can use boolean opeations to get and set the individual values.
It's unclear which bits of your octets apply to which values but you only need & (bitwise AND), | (bitwise OR), << (left shift) and >> (right shift) to do this.
Start from writing a packing/unpacking functions for your 2-byte hybrids.
If you so the work with C/C++ - you may use the intrinsic support for this:
struct Int3 {
int a : 3;
int b : 4;
int c : 3;
};
Bitfields could be one option. You may need to pad your struct to get the bits to line up the way you want them to.
Refer to Bitfields in C++ or search StackOverflow for C++ and bitfields or you can use bitwise operators as outline in the other answers.
Do you mean, if we "concatenate" octets as octet2.octet1, we will get 000000[111][1111][111]?
Then you may use bit operations:
">>" and "<<" to shift bits in your value,
"&" to mask bits
"+" to combine values
For example, "middle" value (which is 4-bits-length) may be received in the following way:
middle = 15 & (octet1 >> 3);
assert(CHAR_BIT == 8);
unsigned int twooctets = (octet2 << 8) | (octet1); /* thanks, Jonas */
unsigned int bits0to2 = (twooctets & /* 0b0000_0000_0111 */ 0x007) >> 0;
unsigned int bits3to6 = (twooctets & /* 0b0000_0111_1000 */ 0x078) >> 3;
unsigned int bits7to9 = (twooctets & /* 0b0011_1000_0000 */ 0x380) >> 7;

Resources