I have created a loop and because it is long, I wanted to see the progress. So, I have added some backspace characters for printing the percentage of the loop on the same line:
std::size_t photoCntr = 0;
for (std::vector< VerifObj >::const_iterator itVOV = verifObjVector.begin(); itVOV != verifObjVector.end(); itVOV++)
{
// some operations
std::cout << "\b\b\b\b" << std::setw(3) << static_cast< int >(100.f * ++photoCntr / verifObjVector.size()) << "%";
}
In the console it is not printing anything until the end of the loop and then it is printing 100%. The loop takes long (some minutes). I am using Ubuntu 14.04 and g++11. Can it be some kind of optimization that do not print until the buffer is full? Any ideas of how to make it work?
You need to flush the output buffer:
std::cout.flush();
You can also use this style:
std::cout << "Stuff" << std::flush;
Just to be thorough, this complete program prints an increasing progress in place:
#include <iostream>
#include <iomanip>
#include <chrono>
#include <thread>
int main() {
for (int i=0; i<100; ++i) {
std::cout << "\b\b\b\b" << std::setw(3) << i << '%' << std::flush;
std::this_thread::sleep_for(std::chrono::milliseconds(30));
}
std::cout << "\b\b\b\b100%" << std::endl;
}
Related
This code is outputting 1 correct answer - which is always the one associated with 'random_number', so the first cout statement is always true. But who wants this kind of a quiz?
srand((int)time(0));
int random_number = rand() % max_event_number;
std::cout <<"\n" << final_years[random_number] << std::endl;
std::cout << "\n" << final_years[1 + random_number] << std::endl;
std::cout << "\n" << final_years[2 + random_number] << std::endl;
std::cout << "\n" << final_years[3 + random_number] << std::endl;
std::cout << "\n" << "Please type the correct year : " << std::endl;
Yes..., I can generate some random answers from the entire array, but they won't necessarily include the correct answer.
I don't want to change the way the correct answer is generated by the first 'random_number', because it takes only one line of code to check if the answer is true or not...
If only I could shuffle every time those 4 cout statement...
How would you do it?
Maybe not the best solution, but it works:
#include <iostream>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <vector>
std::vector<std::string> possible_answers = { final_years[random_number], final_years[1 + random_number], final_years[2 + random_number], final_years[3 + random_number] };
// I initialized a vector like an array with all the 4 answers, including the correct one (since C++11)
std::vector<std::string>::iterator it;
it = possible_answers.begin();
std::random_shuffle(possible_answers.begin(), possible_answers.end()); //shuffled its contents
for (it = possible_answers.begin(); it < possible_answers.end(); it++) //some tinkering to output vector's content
std::cout <<"\n" << *it;
Now the randomly generated numbers are displayed in a random order on the screen, but the correct answer is always the first generated number.
I'm messing around with multithreading in c++ and here is my code:
#include <iostream>
#include <vector>
#include <string>
#include <thread>
void read(int i);
bool isThreadEnabled;
std::thread threads[100];
int main()
{
isThreadEnabled = true; // I change this to compare the threaded vs non threaded method
if (isThreadEnabled)
{
for (int i = 0;i < 100;i++) //this for loop is what I'm confused about
{
threads[i] = std::thread(read,i);
}
for (int i = 0; i < 100; i++)
{
threads[i].join();
}
}
else
{
for (int i = 0; i < 100; i++)
{
read(i);
}
}
}
void read(int i)
{
int w = 0;
while (true) // wasting cpu cycles to actually see the difference between the threaded and non threaded
{
++w;
if (w == 100000000) break;
}
std::cout << i << std::endl;
}
in the for loop that uses threads the console prints values in a random order ex(5,40,26...) which is expected and totally fine since threads don't run in the same order as they were initiated...
but what confuses me is that the values printed are sometimes more than the maximum value that int i can reach (which is 100), values like 8000,2032,274... are also printed to the console even though i will never reach that number, I don't understand why ?
This line:
std::cout << i << std::endl;
is actually equivalent to
std::cout << i;
std::cout << std::endl;
And thus while thread safe (meaning there's no undefined behaviour), the order of execution is undefined. Given two threads the following execution is possible:
T20: std::cout << 20
T32: std::cout << 32
T20: std::cout << std::endl
T32: std::cout << std::endl
which results in 2032 in console (glued numbers) and an empty line.
The simplest (not necessarily the best) fix for that is to wrap this line with a shared mutex:
{
std::lock_guard lg { mutex };
std::cout << i << std::endl;
}
(the brackets for a separate scope are not needed if the std::cout << i << std::endl; is the last line in the function)
Sorry guys forewarning I suck at coding but have a big project and need help!
Input: A complete Sentence.
Output: The sorted order (ASCii Chart Order) of the sentence (ignore case.)
Output a histogram for the following categories:
1) Vowels
2) Consonants
3) Punctuation
4) Capital Letters
5) LowerCase Letters
I have no clue what to even do
Since you are vague in what your issue is, I recommend the following process:
Review Requirements
Always review the requirements (assignment). If there are items you don't understand or have the same understanding as your Customer (instructor), discuss them with your Customer.
Write a simple main program.
Write a simple main or "Hello World!" program to validate your IDE and other tools. Get it working before moving on. Keep it simple.
Here's an example:
#include <iostream>
#include <cstdlib> // Maybe necessary for EXIT_SUCCESS.
int main()
{
std::cout << "Hello World!\n";
return EXIT_SUCCESS;
}
Update program to input text & validate.
Add in code to perform input, validate the input and echo to the console.
#include <iostream>
#include <cstdlib> // Maybe necessary for EXIT_SUCCESS.
#include <string>
int main()
{
std::string sentence;
do
{
std::cout << "Enter a sentence: ";
std::getline(cin, sentence);
if (sentence.empty())
{
std::cout << "\nEmpty sentence, try again.\n\n"
}
} while (sentence.empty());
std::cout << "\nYou entered: " << sentence << "\n";
// Keep the console window open until Enter key is pressed.
std::cout << "\n\nPaused. Press Enter to finish.\n";
std::cin.ignore(100000, '\n');
return EXIT_SUCCESS;
}
Add functionality, one item at a time and test.
Add code for one simple requirement, compile and test.
After it works, make a backup.
Repeat until all requirements are implemented.
For ordering the string you can use standard c qsort function. For counting vowels, consonants, punctuation... you need a simple for loop.
Here is a working example:
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int cmp(const void* pc1, const void* pc2)
{
if(*(char*)pc1 < *(char*)pc2) return -1;
if(*(char*)pc1 > *(char*)pc2) return 1;
return 0;
}
void main(int argc, char* argv[])
{
char pczInput[2000] = "A complete sentence.";
cout << endl << "Input: '" << pczInput << "'";
qsort(pczInput, strlen(pczInput), sizeof(char), cmp);
cout << endl << "Result: '" << pczInput << "'";
int iCapital = 0;
int iLowerCase = 0;
int iPunctuation = 0;
int iVowels = 0;
int iConsonants = 0;
for(unsigned int ui = 0; ui < strlen(pczInput); ++ui)
{
if(isupper(pczInput[ui])) ++iCapital;
if(islower(pczInput[ui])) ++iLowerCase;
if(ispunct(pczInput[ui])) ++iPunctuation;
if(strchr("aeiouAEIOU", pczInput[ui]) != NULL) ++iVowels;
if(strchr("bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ", pczInput[ui]) != NULL) ++iConsonants;
}
cout << endl << "Capital chars: " << iCapital;
cout << endl << "Lower case chars: " << iLowerCase;
cout << endl << "Punctuation chars: " << iPunctuation;
cout << endl << "Vowels chars: " << iVowels;
cout << endl << "Consonants chars: " << iConsonants;
cout << endl;
}
Note that I used C standard functions for counting capital, lower case and punctuation, and I had to use strchr function for counting vowels and consonants because such functions are missing in standard C library.
The output of the program is:
Input: 'A complete sentence.'
Result: ' .Acceeeeelmnnopstt'
Capital chars: 1
Lower case chars: 16
Punctuation chars: 1
Vowels chars: 7
Consonants chars: 10
As you can see in the main function I've created a group of threads that execute the exact same function yet with different parameters. The function simply prints out vector's values. Now the problem is that these threads interfere with one another. What I mean is that one thread does not finish printing (cout) before another starts, and it goes like sdkljasjdkljsad. I want some sort of chaotic order, such as, for example:
Thread 1 Vector[0]
Thread 2 Vector[0]
Thread 1 Vector[1]
Thread 3 Vector[0]
Thread 4 Vector[0]
Thread 2 Vector[1]
Rather than:
Thread 1 Thread 2 Vector[0] Vector[0]
Thread 2 Vector[1]
Thread 1 Thread 4 Vector[1] Thread 3 Vector[0] Vector[1]
How can I solve this problem? P.S. Data file is simply a list of player names, weight and bench-press per line. Transforming these to strings and placing in a vector (yeah, sounds dumb, but I'm just fulfilling a task).
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <string>
#include <thread>
#include <sstream>
#include <iomanip>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
using namespace std;
vector<string> Kategorijos;
vector< vector<string> > Zaidejai;
ifstream duom("duom.txt");
string precision(double a) {
ostringstream out;
out << setprecision(6) << a;
return out.str();
}
void read() {
string tempKat;
int tempZaidSk;
vector<string> tempZaid;
string vardas;
int svoris;
double pakeltasSvoris;
while (duom >> tempKat >> tempZaidSk) {
Kategorijos.push_back(tempKat);
for (int i = 0; i < tempZaidSk; i++) {
duom >> vardas >> svoris >> pakeltasSvoris;
tempZaid.push_back(vardas + " " + to_string(svoris) + " " + precision(pakeltasSvoris));
}
Zaidejai.push_back(tempZaid);
tempZaid.clear();
}
duom.close();
}
void writethreads(int a) {
int pNr = a+1;
for (int i = 0; i < (int)Zaidejai[a].size(); i++) {
cout << endl << "Proceso nr: " << pNr << " " << i << ": " << Zaidejai[a][i] ;
}
}
void print() {
for (int i = 0; i < (int)Kategorijos.size(); i++) {
cout << "*** " << Kategorijos[i] << " ***" << endl;
for (int j = 0; j < (int)Zaidejai[i].size(); j++) {
cout << j+1<<") "<< Zaidejai[i][j] << endl;
}
cout << endl;
}
cout << "-------------------------------------------------------------------" << endl;
}
int main()
{
read();
print();
boost::thread_group threads
;
for (int i = 0; i < (int)Kategorijos.size(); i++) {
threads.create_thread(boost::bind(writethreads, i));
}
threads.join_all();
system("pause");
return 0;
}
Welcome to the problem of thread synchronization! When only one thread can use a resource at a time, the lock you use to control that resource is a mutex. You can also store the data for one thread to output at the end, or you can have the threads synch up at a barrier.
You can synchronise them, the console writes, with an appropriate mutex. But in this case, with the console output, maybe don't use threads at all. Else send the printing to a dedicated thread that deals with it.
The alternative to using the usual cout overloaded operator << is to write the content to a local buffer or stringsteam (including the new line) and then, with a single function call, write that to the console. The single function call will assist in the console writer only writing one buffer's contents at a time.
I want to just hard code these values into a table. when I try to use 2D arrays, I run into the problem of dealing with characters and integers. When I do a struct I have this so far but it doesn't divide the information up in columns, and I'm not sure how to format it that way. (I only did 3 rows to start off with, if I get them working, the rest will just be the same)
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
typedef struct table
{
std::string game;
int year;
float rating;
int num_voters;
}t;
void processTab(t*);
int main()
{
t tabl[2] = {0,0};
int i;
processTab(tabl);
for(i=0; i<2; i++)
{
std::cout << "Game: " << setw(20) << tabl[i].game;
std::cout << "\tYear: " << setw(4) << tabl[i].year;
std::cout << "\tRating: " << fixed << setprecision(2) << tabl[i].rating;
std::cout << "\tVoters: " << setw(6) << tabl[i].num_voters;
}
system("pause");
return 0;
}
void processTab(t*tab)
{
(tab[0].game, "twilight struggles");
tab[0].year = 2005;
tab[0].rating = 8.226;
tab[0].num_voters = 10690;
(tab[1].game, "Agricloa");
tab[1].year = 2007;
tab[1].rating = 8.17;
tab[1].num_voters = 23738;
(tab[2].game, "Puerto Rico");
tab[2].year = 2002;
tab[2].rating = 8.163;
tab[2].num_voters = 27433;
}
Table Data:
Game (0) Year (1) Rating (2) Num Voters (3)
Twilight Struggle 2005 8.226 10690
Agricola 2007 8.17 23738
Puerto Rico 2002 8.163 27433
Through the Ages 2006 8.153 8137
Power Grid 2004 8.02 21655
Le Havre 2008 7.972 9258
Eclipse 2011 7.968 3194
Brass 2007 7.911 5814
Dominion: Intrigue 2009 7.895 10889
Caylus 2005 7.878 13878
What I think you are looking for is <iomanip>
#include <iomanip>
std::cout << "Game: " << setw(20) << tabl[i].game;
std::cout << "\tYear: " << setw(4) << tabl[i].year;
std::cout << "\tRating: " << fixed << setprecision(3) << tabl[i].rating;
std::cout << "\tVoters: " << setw(6) << tabl[i].num_voters;
std::cout << std::end;
Notes:
setw adds padding when writing out stuff, so it will always be at least a certain width
setprecision specifies how many decimal places to display
fixed makes floating point never use scientific notation
Your game member is a letter, and you're attemptying to assign it a string. Don't use strcpy in C++, use the std::string class instead.
#include <string>
struct table
{
std::string game;
int year;
double rating;
int num_voters;
};
Avoid using namespace std;, when you get to complex code with many namespaces, those few letters are a small price to pay for avoiding confusion.
Avoid endl: it flushes buffers which is slow. If you just want a newline, use '\n'.
Also, you can use the new initialization syntax to initialize your list:
std::vector<table> tbal = {
{"twilight struggles ", 2005, 8.226, 10690},
{"Agricola ", 2007, 8.17 , 23738},
{"Puerto Rico ", 2002, 8.163, 27433}
};
Short answer: use std::vector, not a raw array.
The following is as close to your original code as I could make it, introducing a minimum number of new features for you:
#include <assert.h> // assert
#include <iostream> // std::cout, std::endl
#include <stddef.h> // ptrdiff_t
#include <string> // std::string
#include <utility> // std::begin, std::end
#include <vector> // std::vector
using namespace std;
typedef ptrdiff_t Size;
template< class Container >
Size countOf( Container& c ) { return end( c ) - begin( c ); }
struct Game
{
string game;
int year;
double rating;
int num_voters;
};
void initialize( vector<Game>& games )
{
assert( countOf( games ) == 0 );
games.resize( 3 );
games[0].game = "twilight struggles";
games[0].year = 2005;
games[0].rating = 8.226;
games[0].num_voters = 10690;
games[1].game = "Agricloa";
games[1].year = 2007;
games[1].rating = 8.17;
games[1].num_voters = 23738;
games[2].game = "Puerto Rico";
games[2].year = 2002;
games[2].rating = 8.163;
games[2].num_voters = 27433;
}
int main()
{
vector<Game> games;
initialize( games );
for( int i = 0; i < countOf( games ); ++i )
{
cout << i << endl;
cout <<"\tGame: " << games[i].game << endl;
cout<<"\tYear: " << games[i].year << endl;
cout<<"\trating: " << games[i].rating << endl;
cout<<"\tnum voters: " << games[i].num_voters << endl;
}
}
There are ways to just declare the data more directly, including brace initializers; check out your C++ textbook.
First you need to define your table (bad name for a struct, by the way) correctly. You're trying to use game to store a string, but have defined it as only a single char. You probably want to change that to a std::string instead.
Then you probably want to do your formatting in an operator<< overloaded to take a reference to table as the type. #MooingDuck has already covered the formatting itself quite well, so it's mostly a matter of how you package that:
std::ostream &operator<<(std::ostream &os, table const &t) {
os << "Game: " << setw(20) << t.game;
os << "\tYear: " << setw(4) << t.year;
os << "\tRating: " << fixed << setprecision(2) << t.rating;
return os << "\tVoters: " << setw(6) << t.num_voters;
}
Along with that, you almost certainly want to change tabl from an array to std::vector<table>:
std::vector<tabl> tabl;
Then processing the table becomes:
std::copy(tabl.begin(), tabl.end(), std::ostream_iterator<table>(std::cout, "\n"));
One other minor detail: you seem to have two entirely different/separate functions, both named processTab. You probably want to rename at least one of those. Just glancing at them, I'd probably call one initializeTable or something on that order.