Using c++ setw to try to align second column - c++

I'm trying to make sure that the second column in the output is aligned and it seemed like setw would be the solution but not matter what I do the second column is always off. This is the output I get from the code below...
1> 123
10> 234
but I want it to be...
1> 123
10> 234
The only other thing I can think of is to actually get the number of digits of what the actual number of elements are and the index then do some sort of length calc from that. That seems like a lot of handling just to get the second column right aligned.
I also tried << right but since I'm printing line by line in a loop this won't make a difference
int main()
{
int array[2] = {123,234};
int array2[2] = {1, 10};
for(int i = 0; i < 2; i++){
cout << array2[i] << "> " << setw(4) << array[i] << endl;
}
return 0;
}

Using setw ():
You need to set width for the array2[i] element instead of the array[i] element to get the alignment you are looking for.
cout << setw (2) << array2[i] << "> " << array[i] << endl;
Alternative Method 1:
Use printf for formatted printing here.
printf ("%-2d> %4d\n", array2[i], array[i]);
%-2d - the -2 left aligns the integer with width 2.
%4d - the 4 right aligns the integer with width 4.
Alternative Method 2:
Use tabs, or the \t character.
cout << array2[i] << ">\t" << array[i] << endl;
The \t moves your cursor bar to the next tabstop and so you end up getting data aligned in columns like you need. I would not recommend that you use this method because tab widths are unpredictable.

Use a single '\t' character, it TABs automaticly the other column. Example:
for(int i = 0; i < 10; i++)
cout << "x=" << (rand()%10000000+2000)/30 << "\t\ty=" << rand()%2000 << endl;
The output was:
x=+231096 y=+1383
x=+154630 y=+777
x=+141344 y=+1793
x=+325416 y=+1386
x=+321447 y=+649
x=+16400 y=+362
x=+84068 y=+690
x=+250530 y=+1763
x=+12847 y=+540
x=+115257 y=+1172
NOTE: I'm using g++ with flag -std=c++11 for C++11, I don't know its affects results.

Related

How to apply alignment to colored text in c++ output

I am trying to align my output with setw and left in c++ as follows:
string s[] = {"S1", "S2", "S10", "S4", "S5", "S11", "S3", "S7"};
for (int i=4; i<=11; i++) {
for (int j=0; j<8; j++) {
if (j%2==0) {
cout << setw(8) << left << s[i-4];
} else {
cout << setw(8) << left << "* ";
}
}
cout << endl;
}
This code works pretty good. But if I add the color to the text by something like below, it messes up the alignment.
string s[] = {"\033[1;31mS1\033[0m", "\033[1;31mS2\033[0m", "\033[1;31mS10\033[0m", "\033[1;31mS4\033[0m", "\033[1;31mS5\033[0m", "\033[1;31mS11\033[0m", "\033[1;31mS3\033[0m", "\033[1;31mS7\033[0m"};
Anyone have any idea how to fix this code so to have both color and alignment work at the same time? Thanks
If you have strings that you both, want to format, as well as add color codes, then you can do this easily by streaming the color code sequences before you stream the formatted text. This way, the color codes and the alignment won't interfere with each other:
std::cout << "\033[1;31m" << std::setw(8) << std::left << s[i-4] << "\033[0m";
If however, the color codes are part of the strings, then you will have to put in some work to separate the strings from the color codes. Be careful though, since not all color codes have the same number of characters.

cout an array of something separated into columns and rows using \t?

I'm trying to figure out a way to print out a list of memory addresses stored in a file, where there will be 4 or so columns. So it'd print out 4 addresses, each one separated by a '\t', and then do a new line.
I wrote this and it works, except the problem is that once the addresses become 8 long, the tab just gets even wider so it looks bad.
cout << hex;
for (int i = 0; i < getSizeA(); i++) {
fread(&buffer, sizeof(uint32_t), 1, in);
if (i % 4) {
cout << "\t";
}
else {
cout << "\n";
}
cout << buffer;
}
cout << endl << dec;
It looks like this when it's 7 or less
and then the tabs get wider after they're 8 long:
I could probably just add another if statement for that, but it'd probably make my code even more ugly.
Is there a better way to do this than what I'm doing? Namely, a way to separate them using '\t'?

hardcoding 2D array values

Trying to insert values into a 2D array, but the output isnt giving my values, instead random letters
int myArr[8][2] = {700,730,760,790,810,840,910,1000}{0.011,0.035,0.105,0.343,0.789,2.17,20,145};
cout << myArr << endl;
system("Pause");
How should I adjust the code, or is it easier to use a text file and insert?
Numerous problems:
the array dimensions are wrong
you don't have outer braces or a comma for the nested arrays
you're trying to store double precision floating point values in an int array
you can't use cout with an entire array.
The array declaration should probably be something like this:
double myArr[2][8] = { {700,730,760,790,810,840,910,1000},
{0.011,0.035,0.105,0.343,0.789,2.17,20,145} };
and to output the contents you could do something like this:
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 8; ++j)
{
cout << " " << myArr[i][j];
}
cout << endl;
}
Live Demo
First - you can't print the whole array just by using cout << myArr, you need to iterate over the elements of the array using a for loop.
Second - you are trying to put decimal values into an integer array which will truncate all of the decimals.
Third - Your array should be sized myArr[8][2] not myArr[2][8]. I'm surprised your compiler lets you get away with this. You should probably look into using a different compiler.
You need to iterate through each row and column, otherwise you're just printing out the pointer value of the array handle.
for (int i=0;i<8;i++){
for (int j=0;j<2;j++){
cout << myArr[i][j] << " ";
}
cout << endl;
}
system("Pause");

Print "*" up to n terms in pattern and its reverse

I have a problem that is asking for me to write a C++ program using for loops with less than 3 “cout” statements in your code to print the following pattern (ignore the pipes, the asterisks wouldn't appear without them):
|*
|***
|*****
|*******
|*********
|*********
|*******
|*****
|***
|*
This is my code I used for a fibonacci generator and I feel like it might be similar. I am able to print the "*" symbol but not in horizontal lines. What I need most help with is reversing the output. As in if given number n, I want the series to go n numbers into the series and then back down to 0.
#include <iostream>
using namespace std;
int main()
{
int y = 1, sum = 1, n;
cout << "Enter the number of terms you want" << endl;
cin >> n;
cout << "First " << n << " terms are :- " << endl;
for (int x = 0; x < n; x++) {
cout << "\n" <<endl;
for (int i = 0; i < sum; i++) {
cout << "*" << endl;
}
sum = y + 2;
y = sum;
}
}
It seems this is a homework, so I give some hints instead of a full solution.
For printing the *s in one line, please note that << endl will end the line in the output, i.e. print a line break. (The same does << "\n" by the way.) Not every cout statement has to have an << endl at its end.
For reversing the fibonacci sequence, once you have the last number in the variable sum, just do the reverse computation (i.e. subtraction). This could be done in a second set of loops, however, since you should not use cout statements too often, you better reuse the same loop by using some additional variable holding the current state (i.e. if you are counting up or down) and using an if to decide which computation to do. (I read the requirements such that only the cout statements for printing the pattern count to the "less than three" = 2)

Code crashes. Trying to remove characters from char array C

I am basically trying to store everything after a certain index in the array.
For example, I want to store a name which is declared as char name[10]. If the user inputs in say 15 characters, it will ignore the first five characters and store the rest in the char array, however, my program crashes.
This is my code
char name[10];
cout<< "Starting position:" << endl;
cin >> startPos;
for(int i= startPos; i< startPos+10; i++)
{
cout << i << endl; // THIS WORKS
cout << i-startPos << endl; // THIS WORKS
name[i-startPos] = name[i]; // THIS CRASHES
}
For example, if my name was McStevesonse, I want the program to just store everything from the 3rd position, so the end result is Stevesonse
I would really appreciate it if someone could help me fix this crash.
Thanks
Suppose i is equal to 3. In the last iteration of the loop, i is now equal to 12, so substituting 12 in for i, your last line reads
name[12-startPos] = name[12];
name[12] is out of bounds of the array. Based on what you have shown so far, there is nothing but garbage stored in name anyway before you start doing this assignment, so all you're doing is reorganizing garbage in the array.
Please in future: post full compilable example.
A simple answer is that your array maybe is out of bound, since you don't provide full example its hard to know exactly.
Here is a working example:
#include <iostream>
using namespace std;
int main() {
int new_length, startPos;
int length = 15;
char name[15]= "McStevesonse";
cout<< "Starting position:" << endl;
cin >> startPos;
if(new_length <1){ // you need to check for negative or zero value!!!
cout << "max starting point is " <<length-1 << endl;
return -1;
}
new_length=length-startPos;
char newname[new_length];
for(int i= 0; i<new_length; i++){
newname[i] = name[i+startPos]; // THIS CRASHES
}
cout << "old name: " << name << " new name: " << newname << endl;
return 0 ;
}
To put it simply, change this:
for(int i= startPos; i< startPos+10; i++)
To this:
for(int i= startPos; i<10; i++)
You should be fine with that.
Explanation:
At some point, when you use the your old loop, this name[i-startPos] = name[i] would eventually reach an array index out of bounds and causes the crash.
Don't forget to clean up/hide the garbage:
Doing so, would cause the output to produce some kind of garbage outputs. If you got a character array of 'ABCDEFGHIJ', and have chosen 3 as the starting position, the array would be arranged to 'DEFGHIJHIJ'. In your output, you should atleast hide the excess characters, or remove by placing \0's