How can I output a nice neat column? - c++

I want the output format to align-right. My code is as follows.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Planet
{
string name;
double volume;
};
int main(int argc, const char * argv[]) {
Planet planets[3]={{"太阳",22.1e20},{"地球",4.2e7},{"海王星",5.3e10}};
for (int i=0; i<3; i++)
{
cout<<right<<"\t"<<planets[i].name<<setw(12)<<planets[i].volume<<endl;
}
return 0;
}
When I run this code. The output is llike in the picture below, but it's not what I want. Because the output columns cannot align-right.

UPDATE: Question has been updated.
As per documentation, std::right is filling stream from right side and std::setw is for setting width parameter of the stream. In your case, std::right << std::setw(12) must fall just before the thing you want to format(particularly in MacOS X). Thus solution is:
Planet planets[3] = { {"AB",22.1e20},{"AB",4.2e7},{"ABC",5.3e10} };
for (int i = 0; i < 3; i++)
{
cout << right << setw(12) << planets[i].name << right << setw(12) << planets[i].volume << endl;
}
return 0;
This gives Output like this:
My console doesn't support printing of multi-byte characters. That's why i replaced them with characters of same length. If I use them, I get following output but formatting is correct:
Thanks to #Ted ,godbolt has helped me come-up with as generic solution as possible. There seems to be some issue in printing multi-byte characters with std::setw.
Planet planets[5]={{u8"太阳",22.1e20},{u8"地球球",4.2e7},{u8"海王星",5.3e10} , {u8"海王星星",5.3e10} , {u8"海王星星星",5.3e10} };
size_t min_size = 0;
size_t max_size = 0;
for (int i=0; i<5; i++)
{
max_size = max(max_size , planets[i].name.size());
min_size = min(min_size , planets[i].name.size());
}
for (int i=0; i<5; i++)
{
cout << right << setw(max_size + (planets[i].name.size() - min_size)/2 )<< planets[i].name << right << setw( max_size ) << planets[i].volume << endl;
}
This is how it prints:
You could revert printing order of your struct's members and get a better output.

Related

Just need to know if my way of printing pattern in c++ is efficient , or there is an another way to do it efficiently

I have posted a code to print the pattern given below . just need to know if there is another efficient way to do it .
#include<iostream>
#include <string>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++)
{
cout<< string (i+1, '*') << '\n';
}
return 0;
}
This code prints a pattern as drawn below:
*
**
***
****
*****
The most efficient way is:
#include <iostream>
int main()
{
std::cout <<
"*\n"
"**\n"
"***\n"
"****\n"
"*****";
}
You could use lower-level stdio-style calls if you want to avoid the overhead of string manipulations and I/O streams:
#include <stdio.h>
int main(int, char **)
{
for (int i = 1; i <= 5; i++)
{
for (int j = 0; j < i; j++) putc('*', stdout);
putc('\n', stdout);
}
return 0;
}
It's hard to imagine why efficiency would matter here, though.
The following is 4 lines.
#include <iostream>
int main()
{
std::cout << std::setfill('*'); // change fill
for (int i=1; i<= 5; ++i)
std::cout << std::setw(i) << '*' << '\n';
std::cout << std::setfill(' ') << endl; // restore fill
}
I will leave the measurement of run-time comparison to the OP.

Novice C++, seeking help in array division

#include <iostream>
#include <valarray>
using namespace std;
// to get new card number
int main ()
{
int i;
int array[5]= {10,2,6,34,51};
valarray<int> v[5];
int v %= 13;
for (int i=0; i<5 ; i++) {
cout << v[i]%=13 << " ";
}
}
hello, my goal is to get the array to perform a modulus division by number 13.
I've search and try a few different way but I can't figure out a way to make it work.....
Thank you...
Some of the problems with your code:
valarray does not have the same notation as normal arrays: valarray<int> v[5]; declares 5 different valarray objects and puts them in a C-style array. The notation you are looking for is valarray<int> v(10);
Get rid of the int v %= 13; line: this redefines v (an array) as an integer.
Use v[i]=(array[i]%13); for the calculation, what you have doesn't make sense.
Then output cout << v[i] << " ";
Also, you aren't really using any of the features of valarray, so it may make more sense just to use one single array, like:
#include <iostream>
using namespace std;
// to get new card number
int main ()
{
int array[5]= {10,2,6,34,51};
for (int i=0; i<5 ; i++) {
array[i]%=13;
cout << array[i] << " ";
}
}
Edit: by the way, the cool thing about valarray here is that you can apply the same function to every value at once. Like this:
#include <iostream>
#include <valarray>
using namespace std;
int main() {
valarray<int> v(10);
for (int i=0;i<10;++i) {
v[i]=i*i; //Fill the array with 0,1,4,9,16,... as an example
}
v%=13; //This applies the modulo 13 on the whole array at once.
for (int i=0;i<10;++i) {
cout << v[i] << endl;
}
}
Seems you want something like...
int array[5]= {10,2,6,34,51};
int v[5];
for (int i = 0; i < 5; ++i)
v[i] = array[i] % 13;
for (int i = 0; i < 5; ++i)
std::cout << v[i] << " ";
std::cout << '\n';

How to look content of dynamic string array in c++ in VS debugger

What is wrong in this code? I want to make a dynamic string array using string*, not collections, vectors, etc.
int abc = 4;
string* abcdef = new string[abc];
for (int i = 0; i < abc; i++)
{
cin >> abcdef[i];
}
It doesnot give any error but the data I enter is not appearing in locals box in VS2012.
Regards
Oh, looks like your question is about VS debugger.
That's how VS debugger shows contents of a pointer. It doesn't know it's an array, so it just shows you what it points to - the first element. To show all of them in watch window type "abcdef, 4" (where 4 is size of an array, obviously).
This works just fine:
#include <iostream>
#include <string>
int main()
{
int count = 4;
std::string* stringArray = new std::string[count];
for (int i = 0; i < count; i++)
{
std::cin >> stringArray[i];
}
for (int i = 0; i < count; i++)
{
std::cout << "stringArray[" << i << "] = " << stringArray[i] << std::endl;
}
delete [] stringArray;
return 0;
}
Though, the better solution would still be:
int main()
{
std::vector<std::string> stringVector;
std::cout << "Enter Strings (Ctrl-Z to finish):" << std::endl;
std::copy(std::istream_iterator<std::string>(std::cin), std::istream_iterator<std::string>(), std::back_inserter<std::vector<std::string>>(stringVector));
std::copy(stringVector.begin(), stringVector.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}

How to display a progress indicator in pure C/C++ (cout/printf)?

I'm writing a console program in C++ to download a large file. I know the file size, and I start a work thread to download it. I want to show a progress indicator to make it look cooler.
How can I display different strings at different times, but at the same position, in cout or printf?
With a fixed width of your output, use something like the following:
float progress = 0.0;
while (progress < 1.0) {
int barWidth = 70;
std::cout << "[";
int pos = barWidth * progress;
for (int i = 0; i < barWidth; ++i) {
if (i < pos) std::cout << "=";
else if (i == pos) std::cout << ">";
else std::cout << " ";
}
std::cout << "] " << int(progress * 100.0) << " %\r";
std::cout.flush();
progress += 0.16; // for demonstration only
}
std::cout << std::endl;
http://ideone.com/Yg8NKj
[> ] 0 %
[===========> ] 15 %
[======================> ] 31 %
[=================================> ] 47 %
[============================================> ] 63 %
[========================================================> ] 80 %
[===================================================================> ] 96 %
Note that this output is shown one line below each other, but in a terminal emulator (I think also in Windows command line) it will be printed on the same line.
At the very end, don't forget to print a newline before printing more stuff.
If you want to remove the bar at the end, you have to overwrite it with spaces, to print something shorter like for example "Done.".
Also, the same can of course be done using printf in C; adapting the code above should be straight-forward.
You can use a "carriage return" (\r) without a line-feed (\n), and hope your console does the right thing.
For a C solution with an adjustable progress bar width, you can use the following:
#define PBSTR "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
#define PBWIDTH 60
void printProgress(double percentage) {
int val = (int) (percentage * 100);
int lpad = (int) (percentage * PBWIDTH);
int rpad = PBWIDTH - lpad;
printf("\r%3d%% [%.*s%*s]", val, lpad, PBSTR, rpad, "");
fflush(stdout);
}
It will output something like this:
75% [|||||||||||||||||||||||||||||||||||||||||| ]
Take a look at boost progress_display
http://www.boost.org/doc/libs/1_52_0/libs/timer/doc/original_timer.html#Class%20progress_display
I think it may do what you need and I believe it is a header only library so nothing to link
You can print a carriage return character (\r) to move the output "cursor" back to the beginning of the current line.
For a more sophisticated approach, take a look at something like ncurses (an API for console text-based interfaces).
I know I am a bit late in answering this question, but I made a simple class that does exactly what you want. (keep in mind that I wrote using namespace std; before this.):
class pBar {
public:
void update(double newProgress) {
currentProgress += newProgress;
amountOfFiller = (int)((currentProgress / neededProgress)*(double)pBarLength);
}
void print() {
currUpdateVal %= pBarUpdater.length();
cout << "\r" //Bring cursor to start of line
<< firstPartOfpBar; //Print out first part of pBar
for (int a = 0; a < amountOfFiller; a++) { //Print out current progress
cout << pBarFiller;
}
cout << pBarUpdater[currUpdateVal];
for (int b = 0; b < pBarLength - amountOfFiller; b++) { //Print out spaces
cout << " ";
}
cout << lastPartOfpBar //Print out last part of progress bar
<< " (" << (int)(100*(currentProgress/neededProgress)) << "%)" //This just prints out the percent
<< flush;
currUpdateVal += 1;
}
std::string firstPartOfpBar = "[", //Change these at will (that is why I made them public)
lastPartOfpBar = "]",
pBarFiller = "|",
pBarUpdater = "/-\\|";
private:
int amountOfFiller,
pBarLength = 50, //I would recommend NOT changing this
currUpdateVal = 0; //Do not change
double currentProgress = 0, //Do not change
neededProgress = 100; //I would recommend NOT changing this
};
An example on how to use:
int main() {
//Setup:
pBar bar;
//Main loop:
for (int i = 0; i < 100; i++) { //This can be any loop, but I just made this as an example
//Update pBar:
bar.update(1); //How much new progress was added (only needed when new progress was added)
//Print pBar:
bar.print(); //This should be called more frequently than it is in this demo (you'll have to see what looks best for your program)
sleep(1);
}
cout << endl;
return 0;
}
Note: I made all of the classes' strings public so the bar's appearance can be easily changed.
Another way could be showing the "Dots" or any character you want .The below code will print progress indicator [sort of loading...]as dots every after 1 sec.
PS : I am using sleep here. Think twice if performance is concern.
#include<iostream>
using namespace std;
int main()
{
int count = 0;
cout << "Will load in 10 Sec " << endl << "Loading ";
for(count;count < 10; ++count){
cout << ". " ;
fflush(stdout);
sleep(1);
}
cout << endl << "Done" <<endl;
return 0;
}
Here is a simple one I made:
#include <iostream>
#include <thread>
#include <chrono>
#include <Windows.h>
using namespace std;
int main() {
// Changing text color (GetStdHandle(-11), colorcode)
SetConsoleTextAttribute(GetStdHandle(-11), 14);
int barl = 20;
cout << "[";
for (int i = 0; i < barl; i++) {
this_thread::sleep_for(chrono::milliseconds(100));
cout << ":";
}
cout << "]";
// Reset color
SetConsoleTextAttribute(GetStdHandle(-11), 7);
}
May be this code will helps you -
#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <cmath>
using namespace std;
void show_progress_bar(int time, const std::string &message, char symbol)
{
std::string progress_bar;
const double progress_level = 1.42;
std::cout << message << "\n\n";
for (double percentage = 0; percentage <= 100; percentage += progress_level)
{
progress_bar.insert(0, 1, symbol);
std::cout << "\r [" << std::ceil(percentage) << '%' << "] " << progress_bar;
std::this_thread::sleep_for(std::chrono::milliseconds(time));
}
std::cout << "\n\n";
}
int main()
{
show_progress_bar(100, "progress" , '#');
}
Simple, you can just use string's fill constructor:
#include <iostream> //for `cout`
#include <string> //for the constructor
#include <iomanip> //for `setprecision`
using namespace std;
int main()
{
const int cTotalLength = 10;
float lProgress = 0.3;
cout <<
"\r[" << //'\r' aka carriage return should move printer's cursor back at the beginning of the current line
string(cTotalLength * lProgress, 'X') << //printing filled part
string(cTotalLength * (1 - lProgress), '-') << //printing empty part
"] " <<
setprecision(3) << 100 * lProgress << "%"; //printing percentage
return 0;
}
Which would print:
[XXX-------] 30%
If you need it in pure C
and you would like to be able to customize the size and filler characters at runtime:
#include <stdio.h> //for `printf`
#include <stdlib.h> //for `malloc`
#include <string.h> //for `memset`
int main()
{
const int cTotalLength = 10;
char* lBuffer = malloc((cTotalLength + 1) * sizeof *lBuffer); //array to fit 10 chars + '\0'
lBuffer[cTotalLength] = '\0'; //terminating it
float lProgress = 0.3;
int lFilledLength = lProgress * cTotalLength;
memset(lBuffer, 'X', lFilledLength); //filling filled part
memset(lBuffer + lFilledLength, '-', cTotalLength - lFilledLength); //filling empty part
printf("\r[%s] %.1f%%", lBuffer, lProgress * 100); //same princip as with the CPP method
//or you can combine it to a single line if you want to flex ;)
//printf("\r[%s] %.1f%%", (char*)memset(memset(lBuffer, 'X', lFullLength) + lFullLength, '-', cTotalLength - lFullLength) - lFullLength, lProgress * 100);
free(lBuffer);
return 0;
}
but if you don't need to customize it at runtime:
#include <stdio.h> //for `printf`
#include <stddef.h> //for `size_t`
int main()
{
const char cFilled[] = "XXXXXXXXXX";
const char cEmpty[] = "----------";
float lProgress = 0.3;
size_t lFilledStart = (sizeof cFilled - 1) * (1 - lProgress);
size_t lEmptyStart = (sizeof cFilled - 1) * lProgress;
printf("\r[%s%s] %.1f%%",
cFilled + lFilledStart, //Array of Xs starting at `cTotalLength * (1 - lProgress)` (`cTotalLength * lProgress` characters remaining to EOS)
cEmpty + lEmptyStart, //Array of -s starting at `cTotalLength * lProgress`...
lProgress * 100 //Percentage
);
return 0;
}
I needed to create a progress bar and some of the answers here would cause the bar to blink or display the percentage short of 100% when done. Here is a version that has no loop other than one that simulates cpu work, it only prints when the next progress unit is incremented.
#include <iostream>
#include <iomanip> // for setw, setprecision, setfill
#include <chrono>
#include <thread> // simulate work on cpu
int main()
{
int batch_size = 4000;
int num_bars = 50;
int batch_per_bar = batch_size / num_bars;
int progress = 0;
for (int i = 0; i < batch_size; i++) {
if (i % batch_per_bar == 0) {
std::cout << std::setprecision(3) <<
// fill bar with = up to current progress
'[' << std::setfill('=') << std::setw(progress) << '>'
// fill the rest of the bar with spaces
<< std::setfill(' ') << std::setw(num_bars - progress + 1)
// display bar percentage, \r brings it back to the beginning
<< ']' << std::setw(3) << ((i + 1) * 100 / batch_size) << '%'
<< "\r";
progress++;
}
// simulate work
std::this_thread::sleep_for(std::chrono::nanoseconds(1000000));
}
}

Print struct element of vector

I am learning about vector. I try to implement a code that print the struct element of a vector as displayed below. Many resources in the internet only teach me a simple vector. I get stcuk in expression when to print it. However, any suggestion for improving the quality and elegance of the code is open, although the change is fundamental (in struct or looping).
Thank you very much.
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
typedef struct _student {
string name;
int age;
vector <string> subject;
}student;
int _tmain(int argc, _TCHAR* argv[])
{
vector <student> x; //assmue at this point we do not know the number of students
student y;
//and I want to insert new information
y.name ="John";
y.age =9;
y.subject.push_back("biology");
y.subject.push_back("math");
y.subject.push_back("art");
x.push_back(y);
//get new information again
//and I want to insert new information
y.name ="Bon";
y.age =12;
y.subject.push_back("history");
y.subject.push_back("physics");
x.push_back(y);
// then I want display all data
cout << "myvector contains:";
for (int i=0; i<x.size(); i++)
{
cout << "Student # " << i+1 <<endl;
cout << " name : " << x.at(i).name <<endl; //Reference in the internet only display a simple vector --
cout << " age : " << x.at(i).age <<endl; //I get stuck to express this and next part
cout <<" Subject : ";
for (int j =0; j < x.at(i).subject.size(); j++)
{
cout << x.at(i).subject.at(j);
}
cout << endl;
cin.get();
return 0;
}
Here, added some comments and stuff. Not sure if this is what you were looking for, but here it is.
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string> // string would be welcome here!
struct _student // the typedef thing is not necessary in C++
{
std::string name; // i find this "using namespace ..." thing a bad habit, it can make code harder to read
int age;
std::vector<std::string> subject;
};
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<student> x;
student y;
size_t size; // calling vector.size() every iterations is a bad idea, performance-wise
size_t size_subj; // same
y.name = "John";
y.age = 9;
y.subject.push_back("biology");
y.subject.push_back("math");
y.subject.push_back("art");
x.push_back(y);
y.name = "Bon";
y.age = 12;
y.subject.clear(); // clear subjects of the other student
y.subject.push_back("history");
y.subject.push_back("physics");
x.push_back(y);
std::cout << "my vector contains:";
for (int i = 0, size = x.size(); i < size; ++i)
{
size_subj = x[i].subject.size();
// I prefer using operator[] when I'm sure nothing can go wrong
std::cout << "Student # " << i + 1 <<endl;
std::cout << "\tname: " << x[i].name <<endl;
std::cout << "\tage: " << x[i].age <<endl;
std::cout << "\tSubjects: ";
for (int j = 0; j < size_subj; ++j)
std::cout << x[i].subject[j];
std::cout << endl;
}
return 0;
}
Finally, using a std::vector< std::string* > or std::vector< std::string& > could be a better idea performance-wise, depending on what you are planning to do with it later.
There is no real question here, so I'm assuming you are asking for "code review"
The "neat" way is of course to create an operator<< that takes your inner structure.
Aside from that, you may want to look at using iterators to walk your way through your vector - that way, you should be able to change your vector for any other container type without having to change the loop(s) that print things.
Use longer variable names than x and y for your vector and temporary student.
Use setw to print fields at the same width every time.
I'm sure there are plenty of other suggestions too.
As the comments point to, it turns out that you're not including the string header file.