using gotoxy positioning in a "for loop" - c++

int strtnumber,endnumber,remainder,i;
gotoxy(2, 0);
printf("Enter Start value: "); //enters start number
cin >> strtnumber;
gotoxy(2, 1);
printf("Enter End Value: "); //enters end number
cin >> endnumber;
cout << "==================================================="<< endl;
for (; strtnumber <= endnumber; strtnumber++) {
remainder = strtnumber % 2;
if (remainder == 1) {
cout << strtnumber << endl;
}
if (remainder == 0) {
cout << strtnumber << endl;
}
}
I would like to separate the odd and even numbers using gotoxy
This is the output I would like to achieve:
ODD | EVEN
1 | 2
3 | 4
5 | 6

I would like to separate the odd and even numbers using gotoxy This is
the output I would like to achieve:
Almost every system with which I have worked has ansi terminal's available. Even the embedded systems would be connected (via RS232) to VT100's or equivalent.
PC's come equipped with ansi term emulators, or the emulators can be trivially downloaded and installed.
Note: The comments provided are clear, Ansi i/o is not part of C++.
But you can easily find example code to invoke the ansi terminal functions you might want.
Here is a useful part of my own class which has worked on every version of Ubuntu Linux, and multiple Linux terminal emulators, and vxWorks, etc. I currently use an emulator installed with Lubuntu. Have not found the name, but the help references Qt_io:
#include <iostream>
using std::cout, std::endl;
#include <string>
using std::string, std::to_string;
class Ansi_t // provide access to features of ansi-compatible terminal
{
public:
string clrscr (void)
{ return '\033' + string("[H") + '\033' + string("[2J"); }
// --v------v- C++ 2d array indexing is 0 based
string gotoRC(int r, int c) {
return ('\033' + string("[") +
to_string(r+1) + ';' + to_string(c+1) + 'H');
} // 0 ^ 0 ^
// 1,1 is top left of ansi screen
// tbr - add other ansi functions here
}; // class Ansi_t
// usage: declare an instance, Ansi_t ansi;
// invoke method: std::cout << ansi.clrscr() << std::endl;
// invoke method: std::cout << ansi.gotoRC() << std::endl;
// to specify a named escape sequence ^^^^^^^^
// Ubuntu gnome-terminal ansi term cursor locations are
// 1-based with origin 1,1 at top left corner
class Hello_t // demo executable
{
Ansi_t ansi; // declare an instance
public:
Hello_t() { cout << ansi.clrscr() << ansi.gotoRC(9, 18) << "Hello "; }
~Hello_t() { cout << " world!\n\n\n" << endl; }
int operator()() { cout << "C++"; return 0; } // functor entrance
};
int main(int , char* * ) { return (Hello_t()()); }

Related

How do I delete a line text which has already been written on the terminal in c++?

I am currently making a Self Service Order Payment Program for a project and I was trying to figure out a way to erase the previous line of text to make it look cleaner. I discovered there was a similar function to system("CLS"); but instead of erasing all the text in the console, it only erases certain parts of the text.
I've been coding for about a week or two so if I missed anything please tell me.
switch(buy){
case '1':
//random code
break;
default:
cout << "sorry thats not a valid number ;w;\n\n"; //remove this text after system("pause")
system("pause");
system("CLS"); //I need this to remove only one line instead of the whole thing.
break;
}
The \ns at the end of this line makes it hard to remove the text on the line using only standard control characters:
cout << "sorry thats not a valid number ;w;\n\n";
Also, the system("pause"); is non-standard and will likely also result in a newline (I'm not sure about that).
What you could do is to skip the printing of \n and to just sleep a little before continuing.
Example:
#include <chrono> // misc. clocks
#include <iostream>
#include <string>
#include <thread> // std::this_thread::sleep_for
// a function to print some text, sleep for awhile and then remove the text
void print_and_clear(const std::string& txt, std::chrono::nanoseconds sleep) {
std::cout << txt << std::flush; // print the text
std::this_thread::sleep_for(sleep); // sleep for awhile
// Remove the text by returning to the beginning of the line and
// print a number of space characters equal to the length of the
// text and then return to the beginning of the line again.
std::cout << '\r' << std::string(txt.size(), ' ') << '\r' << std::flush;
}
int main() {
print_and_clear("sorry thats not a valid number...", std::chrono::seconds(1));
std::cout << "Hello\n";
}
The above will print your text, sleep for a second, then remove the text and continue. What's left on the screen after the program has executed is only Hello.
you need to declare a variable and then use if condition.
i don`t know c++ but i give to hint here.
bool systempaused=false;
later on
if(!systempaused)
{
//print your line
}
system("pause")
You can do:-
cout<<"\r lots of spaces "<<endl;
basically what \r escape sequence does is that it brings the cursor to the start of the line. If you print anything after printing \r it will overwrite what was already on that line
As I know there are no standard C++ only solutions for your task, there are platform-dependend ways that I'll describe below.
Main thing needed to achieve your task is to move cursor one line up. Afterwards you can just print spaces to clear line (and move cursor to start of line through \r).
I provide two next variants (Variant 1 and Variant 2) of solving your task.
Variant 1. Using ANSI escape codes (Windows/Linux/MacOS).
There are so-called ANSI escaped codes that allow you to do rich manipulations of console. Including your task (moving cursor one line up).
Through this escape codes moving line up is achieved by printing string "\x1b[1A" to console (to move e.g. 23 lines up you may print "\x1b[23A", see 23 inside this string). Also you may want to move cursor to right, this is achieved through "\x1b[23C" (to move 23 positions to right).
By default Linux/MacOS and other POSIX systems usually support ANSI escape codes (different terminal implementations may or may not support them). Windows also supports ANSI escape codes but they are not enabled by default, it needs to be enabled by special WinAPI functions.
Inside ClearLines() function don't forget to tweak width argument, it is set to 40 right now, it signifies width of your console, precisely it clears only first width chars of line with spaces.
Next code does what you need for Windows and Unix systems. Windows-specific code is located between #ifdef and #endif.
Try it online!
#include <iostream>
#include <cstdlib>
#ifdef _WIN32
#include <windows.h>
inline bool WinAnsiConsoleEnable(int stdout_or_stderr = 0) {
if (!SetConsoleOutputCP(65001)) // Enable UTF-8 console if needed.
return false;
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
DWORD outMode = 0;
HANDLE stdoutHandle = GetStdHandle(stdout_or_stderr == 0 ?
STD_OUTPUT_HANDLE : stdout_or_stderr == 1 ? STD_ERROR_HANDLE : 0);
if (stdoutHandle == INVALID_HANDLE_VALUE)
return false;
if (!GetConsoleMode(stdoutHandle, &outMode))
return false;
// Enable ANSI escape codes
outMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if (!SetConsoleMode(stdoutHandle, outMode))
return false;
return true;
}
#endif // _WIN32
static void ClearLines(size_t cnt, size_t width = 40) { // Clears cnt last lines.
std::cout << "\r";
for (size_t i = 0; i < cnt; ++i) {
for (size_t j = 0; j < width; ++j)
std::cout << " ";
std::cout << "\r";
if (i + 1 < cnt)
std::cout << "\x1b[1A"; // Move cursor one line up, ANSI sequence.
}
}
int main() {
#ifdef _WIN32
if (!WinAnsiConsoleEnable()) {
std::cout << "Error enabling Win ansi console!" << std::endl;
return -1;
}
#endif
bool good = false;
char buy = 0;
std::cout << "Enter number:" << std::endl;
while (!good) {
std::cin >> buy;
switch (buy) {
case '1': {
std::cout << "Valid number." << std::endl;
good = true;
break;
}
default: {
std::cout << "Sorry thats not a valid number!\n";
#ifdef _WIN32
std::system("pause");
#else
std::system("read -p \"Press enter to continue . . . \" x");
#endif
ClearLines(4);
break;
}
}
}
}
Output (shown on Linux, Windows is same) (+ ascii-video):
Variant 2. Using WinAPI functions (Windows-only).
Next variant works only for windows and uses only WinAPI console manipulation functions (no ANSI escapes).
#include <iostream>
#include <cstdlib>
#include <windows.h>
// Moves cursor by (DeltaX, DeltaY) = (offx, offy) relative to current position.
inline bool WinMoveCursor(int offx, int offy) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO cbsi = {};
if (!GetConsoleScreenBufferInfo(hConsole, &cbsi))
return false;
COORD coord = cbsi.dwCursorPosition;
coord.X += offx;
coord.Y += offy;
if (!SetConsoleCursorPosition(hConsole, coord))
return false;
return true;
}
static void ClearLines(size_t cnt, size_t width = 40) { // Clears cnt last lines.
std::cout << "\r";
for (size_t i = 0; i < cnt; ++i) {
for (size_t j = 0; j < width; ++j)
std::cout << " ";
std::cout << "\r";
if (i + 1 < cnt)
WinMoveCursor(0, -1); // Move cursor one line up, WinAPI.
}
}
int main() {
SetConsoleOutputCP(65001); // Enable UTF-8 if needed.
bool good = false;
char buy = 0;
std::cout << "Enter number:" << std::endl;
while (!good) {
std::cin >> buy;
switch (buy) {
case '1': {
std::cout << "Valid number." << std::endl;
good = true;
break;
}
default: {
std::cout << "Sorry thats not a valid number!\n";
std::system("pause");
ClearLines(4);
break;
}
}
}
}

How to use MPIR Prime testers mpz_likely_prime_p and mpz_probable_prime_p?

I'm trying to use MPIR's prime tester(s) for rapid non-sequential testing; however, I'm new to MPIR and am confused about their usage - specifically the "gmp_randstate_t" parameter used by the function. Here's what I've got so far:
#include<iostream> // used for cout
#include<mpir.h>
int main() {
mpz_t PrimeCanidate;
mpz_init(PrimeCanidate);
mpz_set_ui(PrimeCanidate, 3); // sets PrimeCanidate to unsigned int "3"
if (mpz_likely_prime_p(PrimeCanidate) == 1) {
std::cout << "Number is prime: " << std::endl;
}
}
As I'm only using one parameter inside mpz_likely_prime_p, it doesn't work - I just don't know what it's looking for with the other parameters (state, div) as shown in the documentation (http://www.mpir.org/mpir-3.0.0.pdf pg. 42):
Would anybody by chance have a simple code that uses the prime-testing functions in MPIR? Thanks a ton.
After a bunch of tinkering, I figured out how to properly initialize the "state" and div" parameters for mpz_likely_prime_p. Here's an example calculating and printing primes between 1 and 100:
#include<iostream> // used for cout
#include<mpir.h>
int main() {
mpz_t PrimeCanidate;
mpz_init(PrimeCanidate);
mpz_set_ui(PrimeCanidate, 2);
mpz_t additor;
mpz_init(additor);
mpz_set_ui(additor, 1);
gmp_randstate_t state;
gmp_randinit_default(state);
mpir_ui div = 0;
int maxbase = 100;
for (int base = 2; base < maxbase; base++) {
mpz_add(PrimeCanidate, PrimeCanidate, additor); // repeatedly adds one to PrimeCanidate
std::cout << "Tested Number: " << PrimeCanidate << std::endl;
if (mpz_likely_prime_p(PrimeCanidate, state, div) == 1) {
std::cout << PrimeCanidate << " is prime." << std::endl;
}
}
}
This is probably not optimal, but it works and might be a good place to start.

Reading into an Array Multiple Times

I'm having a little trouble with my code. It's pretty much supposed to open two files, and compare the first twenty line of the file "StudentAnswers.txt" [inputted as a char into a char array] against a char value in (each line of another file) "CorrectAnswers.txt" in another array at the same position (index). It's like a linear search, but the same position in the arrays. Then a report should be displayed, detailing which question the student missed, the given answer, the correct answer, and if the student passed (got >= 70%) or not, like the following:
Report for Student X:
2 (A/D), 3 (C/D), 5(D/A)
This student passed the exam!
Then it should clear the SAArray, and feed the next twenty lines from StudentAnswers.txt, and start the process all over again. I guess the program has to determine the number of students from (lines of 'StudentAnswers.txt' file / 20).
I'm having trouble displaying the report, and having the array clear itself after the program. I'm guessing this can be done with a while loop and an accumulator for the number of students (to be determined by above equation).
Also, Visual Studio seems to go to "Missed __ questions for a total of ___ %", and then keep looping -858993460.
Any help would be appreciated.
#include <iostream>
#include <fstream>
#include <string>
#include <array>
#include <algorithm>
using namespace std;
void GradeReturn(char[], char[], int, int, int);
string PassFail(float);
int main()
{
ifstream SA("StudentAnswers.txt");
ifstream CA("CorrectAnswers.txt");char CAArray[20];
char SAArray[20];
// char SA2Array[20];
bool isCorrect;
int correct;
int incorrect;
int counter;
correct = 0;incorrect = 0;
counter = 0;
cout << endl;
if (!SA.fail())
{
cout << "'StudentAnswers.txt' file opened successfully." << endl;
cout << "'CorrectAnswers.txt' file opened successfully." << endl << endl;
int a = 0;
int b = 0;
while (a < 20)
{
CA >> CAArray[a];
a++;
} // while loop to feed char into the array
while (b < 20)
{
SA >> SAArray[b];
b++;
}
} // while loop to feed char into array
CA.close(); // closing "CorrectAnswers.txt"
SA.close(); // closing "StudentAnswers.txt"
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter);
return 0;
}
void GradeReturn(char CAArray[], char SAArray[], int correct, int incorrect, int counter)
{
float percent;
float hundred;
int student;
int catcher[20];
int writeCatcher; int starter;
int catcher_size;
student = 0;
writeCatcher = 0;
catcher_size = ((sizeof catcher) / 4);
while (counter < 20)
{
if ((CAArray[counter]) == (SAArray[counter]))
{
correct++;
cout << "Good job!" << endl;
} // correct handling
else
{
incorrect++;
cout << "You got question " << counter << " wrong." << endl;
counter >> catcher[writeCatcher];
writeCatcher++;
} // incorrect handling
counter++;
} // while loop to determine if a student got a question right or wrong
static_cast <float> (incorrect); // float conversion
cout << endl; // for cleanliness
percent = ((static_cast <float> (correct)) / 20); // percentage
hundred = percent * 100;
PassFail(percent);
if (PassFail(percent) == "pass")
{
student++;
cout << "Report for Student " << student << ":" << endl;
cout << "-----------------------------" << endl;
cout << "Missed " << incorrect << " questions out of 20 for ";
cout << hundred << " % correct." << endl << endl;
starter = 0;
while (starter < (sizeof catcher)
{
if(1=1)
{
catcher_size
}
else
{
cout << "";
starter++;
}
}
}
else if (PassFail(percent) == "fail")
{
student++;
cout << "Missed " << incorrect << " questions out of 20 for ";
cout << hundred << " % correct." << endl << endl;
while (starter < catcher_size)
{
if ((catcher[starter]) == -858993460)
{
starter++;
}
else
{
cout << "";
starter++;
}
}
}
return;
}
string PassFail(float percent)
{
if (percent >= 0.70) // if <pass>
{
return "pass";
}
else // if <fail>
{
return "fail";
}
cout << endl;
}
To get a loop you should keep streams open instead of closing them after reading 20 lines.
As pseudo code that would be:
a = 0;
while(streams_not_empty)
{
CA >> CAArray[a];
SA >> SAArray[a];
++a;
if (a == 20)
{
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter);
a = 0; // Reset a
}
}
CA.close(); // closing "CorrectAnswers.txt"
SA.close(); // closing "StudentAnswers.txt"
You would also need to pass correct, incorrect, counter by reference so that the GradeReturn can change their value and their by do the accumulation.
Like:
void GradeReturn(char CAArray[], char SAArray[], int& correct, int& incorrect, int& counter)
Further you shouldn't rely on being able to read exactly Nx20 lines from the files every time. A file could have, e.g. 108 (5x20 + 8) lines, so you code should be able to handle the with only 8 lines. In other words, don't hard code 20 in your function like while (counter < 20). Instead pass the number of lines to be handled and do while (counter < number_to_handle).
Something like this as pseudo code:
a = 0;
while(streams_not_empty)
{
CA >> CAArray[a];
SA >> SAArray[a];
++a;
if (a == 20)
{
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter, a);
// ^
a = 0; // Reset a
}
}
if (a != 0)
{
// Process the rest
GradeReturn(&CAArray[counter], &SAArray[counter], correct, incorrect, counter, a);
}
CA.close(); // closing "CorrectAnswers.txt"
SA.close(); // closing "StudentAnswers.txt"
One problem you have is you're trying to compare C-style strings with the == operator. This will compare them essentially as if they were pointers to char, i.e. compare whether they point at the same location in memory, not compare the contents of the string. I urge you to look up array-decay and c-string variables to understand more.
Specifically, if (PassFail(percent) == "pass") isn't going to do what you want it to. strcomp doc, strncmp doc using std::string variables instead of c-style strings would all work, but it would be better simply to compare percent to a value, i.e. if(percent >= 0.70 directly instead of calling PassFail and comparing a string.
There are many other issues here also, you at one point call PassFail but do nothing with the return value. The only side affect of PassFail is cout << endl, if that's what you intend, it's a poor decision and hard to read way to put a newline on the console.
Try asking your compiler for more warnings, that's often helpful in finding these types of issues. -Wall -Wextra work for gcc, you may have to read your compiler manual...

Parsing an edge list into a vector of structs

I am having a hard time parsing an edge list from a text file in c++. The edge list is in the following format:
*Edgeslist
1 6487
2 6488 6489 6490 6491 6492 6493 6494 6495 6496
3 6497 6498 6499 6500 6501 6502 6503 6504 6505
4 6506 6507 6508
5 6509 6510 6511
6 6512 6513 6514 6515
7 6516
8 6517 6518
9 6519 6520
10 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535
11 6566
My vector is a vector of structs that is defined here
struct Edge{
int character;
int edges[16];
};
The first number of each line should be read into the character integer and the rest should be read into the edges array. I have tried a few for loops, and currently working on a lengthy while loop with if statements for each number of possible integers to go into the array (max of 15 integers per line after the first number). Here is a part of my implementation so you can see what I am attempting.
while(std::getline(input, line))
{
int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;
std::stringstream ss(line);
if ( ss >> a)
{
std::cout << "1 " << a << "\n";
}
if ( ss >> a >> b)
{
std::cout << "2 " << a << " " << b << "\n";
}
if ( ss >> a >> b >> c)
{
std::cout << "3 " << a << " " << b << " " << c << "\n";
}
if ( ss >> a >> b >> c >> d)
{
std::cout << "4 " << a << " " << b << " " << c << " " << d << "\n";
}
I'll end it there but it does go on for awhile until it covers every possible line.
At the moment I am just trying to figure out the basic logic to parse this text file.
You have tagged this as C++.
I would recommend you add an initializer if you must continue with pod ...
struct Edge
{
int character;
int edges[16];
// more data attributes
// use ctor to initialize these values
Edge(void) :
character (0)
// edges[16]
{
for (int i=0; i<16; ++i)
edges[i] = 0;
}
// use dtor to clear them
~Edge(void)
{
for (int i=0; i<16; ++i)
edges[i] = 0;
character = 0;
// ...
}
};
I suspect you will also need a count of how many edges have currently been in installed (or perhaps call it nextIn).
The fundamentally important signature of C++ code is the preferred use of objects-defined-by-a-class. I recommend you consider:
struct Edge
{
int character; // poor name choice
std::vector<int> edges; // << use vector, not array
// use ctor to initialize these values
Edge(void) :
character (0)
// edges // default ctor does what you need
{
}
~Edge(void) {
// edges default dtor does what you need
character = 0;
}
};
The std::vector reduces your work to read arbitrary counts of values.
// Typical input:
// 3 6497 6498 6499 6500 6501 6502 6503 6504 6505
// 4 6506 6507 6508
#include <iostream>
#include <iomanip>
#include <sstream>
#include <vector>
struct Edge
{
int character; // <<< poor name choice
std::vector<int> edges; // <<< use vector, not array
// use ctor to initialize these values
Edge(void) :
character (0)
// edges default ctor does what you need
{
}
~Edge(void) {
// edges default dtor does what you need
character = 0;
}
bool ok(void) {
/*tbd - count errors? size check? */
return(true);
};
void load(std::string line)
{
// typical input line
// 3 6497 6498 6499 6500 6501 6502 6503 6504 6505
// 4 6506 6507 6508
std::stringstream ss(line+' ');
// padding at end ---------^----because ss.eof() sooner than I expected
//debug only
//std::cout << " in: (" << std::setw(3) << line.size() << ")
// << line << std::endl;
// process one work buff
do {
ss >> character; // read 1st int of line
if (ss.eof()) break;
if (ss.bad()) {
// maybe invalid integer format
std::cerr << "bad input: " << line << std::endl;
// tbd - error count?
break;
}
// process 1 or more entries for edge.vector from line
do {
int edgeVal = 0;
ss >> edgeVal;
if (ss.eof()) break;
if (ss.bad()) {
// maybe invalid integer format
std::cerr << "bad input: " << line << std::endl;
// tbd - error count?
break;
}
// additional edgeVal validations?
edges.push_back(edgeVal); // fill in one value to edge vector
// add validation here if edges.size() has an upper limit
// tbd - error count?
} while (1); // // process 1 or more entries to vector from line
} while(1); // one work buff
// debug only
dump();
} // void load(std::stringstream& ss, std::string line)
// for debug
void dump()
{
std::cout << "dump: (" << std::setw(3) << edges.size()
<< ") " << character << " ";
for (size_t i=0; i<edges.size(); ++i)
std::cout << edges[i] << " ";
std::cout << std::endl;
}
}; // struct Edge()
int t237(void)
{
std::vector<Edge> edgeVec;
// file processing at outer scope
do {
std::string line; // work buff
(void)std::getline(std::cin, line);
if(std::cin.eof()) break;
std::stringstream ss(line);
Edge temp; // a work buff
temp.load(line); // <<< load method for Edge (part of Edge)
// not sure where to put all the Edge objects
// temporarily, use edgeVec;
if (temp.ok()) // add flag check that edgeVec had no errors
edgeVec.push_back(temp);
else
/*tbd*/{}; // error in temp ... discard it? report it?
} while (1);
// tbd - how return vector and file status
return (0);
}
---- update
ss.eof() occurring before I expected ... added "padding at end"
added dump() debug method, added debug cout of input line
minimal testing complete
You should split your string into substrings at whitespaces. Details are explained here.
After that, you just cast your substrings to appropiate type.
std::stringstream ss(line);
ss >> character;
unsigned int n=0;
while(ss >> edges[n])
{
++n;
}
(One could make this a little shorter, but that would make it less readable.)

Structured output

I recently started programming in c++ and I've bumped into a small problem. If I want my output to be structured (let's say that every line starts with a name and then a number) in a way that the names are written normally to the screen (every first letter of every name starts at the beginning of each new line) and I want the numbers that follow to be lined up in a column, how would I do this? I want the programs output to look like this:
Gary 0
LongName 0
VerylongName 0
I want my program to print something in the way above, but with different lengths of names (and the '0' in this case, lined up in a column).
Try the following: if you know the maximum length of all the names you intend to print (e.g. 20), then use the C++ i/o manipulators to set the width of the output (and left-justification). This will force the output to take up max characters.
Code snippet:
#include <iostream>
#include <iomanip>
...
// for each entry
std::cout << std::setw(20) << std::left << "Gary" << 10 << "\n";
...
std::cout << std::flush;
Here's some more information...
I'm shooting in the dark here since you haven't really included much information... HOWEVER one way you can do this is to make sure that you create the columns with padding around the name - and not worry about the numbers. Formatted output is one case where C has an advantage over C++ (IMHO). In C++ you can also do this with something like this:
cout << setw(15) << name << number << "\n";
Bonus points if you figure out ahead of time the maximum length of the name you have and add, say, 4 to it.
Not in the C++ standard library, but still worth mentioning: boost::format. It will let you write printf-like format strings while still being type-safe.
Example:
#include <boost/format.hpp>
#include <iostream>
#include <string>
struct PersonData
{
std::string name;
int age;
};
PersonData persons[] =
{
{"Gary", 1},
{"Whitney", 12},
{"Josephine ", 101}
};
int main(void)
{
for (auto person : persons)
{
std::cout << boost::format("%-20s %5i") % person.name % person.age << std::endl;
}
return 0;
}
Outputs:
Gary 1
Whitney 12
Josephine 101
struct X
{
const char *s;
int num;
} tab[] = {
{"Gary",1},
{"LongName",23},
{"VeryLongName",456}
};
int main(void)
{
for (int i = 0; i < sizeof(tab) / sizeof(struct X); i++ )
{
// C like - example width 20chars
//printf( "%-20s %5i\n", tab[i].s, tab[i].num );
// C++ like
std::cout << std::setw(20) << std::left << tab[i].s << std::setw(5) << std::right << tab[i].num << std::endl;
}
getchar();
return 0;
}