how to print on the same line inside function, avoid flush - c++

I want to display a progress bar however putting the printing code inside a separate function seems to invoke an std::flush as each time the progress bar is printing in a new line. This did not happen when the code was used inline
The code:
#include <iostream>
#include <unistd.h>
void load(int curr, int total) {
std::cout << "\n[";
int pos = 50 * curr/total;
for (int i = 0; i < 50; ++i) {
if (i < pos) std::cout << "=";
else if (i == pos) std::cout << ">";
else std::cout << " ";
}
std::cout << "]" << int(float(curr)/(float)total * 100.0) << " %\r";
std::cout.flush();
}
int main(){
for( int i = 0; i <= 5; i++ ){
load(i,5);
}
std::cout << std::endl;
return 0;
}
What it does:
[> ]0 %
[==========> ]20 %
[====================> ]40 %
[==============================> ]60 %
[========================================> ]80 %
[==================================================]100 %
What it's supposed to do: print all on the same line

The first line in your function outputs \n, which is what makes it print on a new line every iteration.
Fix:
#include <iostream>
void load(int curr, int total) {
std::cout << '[';
int pos = 50 * curr/total;
for (int i = 0; i < 50; ++i) {
if (i < pos) std::cout << '=';
else if (i == pos) std::cout << '>';
else std::cout << ' ';
}
std::cout << ']' << int(float(curr)/(float)total * 100.0) << " %\r" << std::flush;
}
int main(){
for( int i = 0; i <= 5; i++ ){
load(i, 5);
}
std::cout << '\n';
}

Related

How to format output like this

My code is like this so far :
void matrix::print(int colWidth) const
{
cout << getRows() << " x " << getCols() << endl;
cout << "-";
for (unsigned int d = 0; d < getCols(); d++) {
cout << "--------";
}
cout << endl;
for (unsigned x = 0; x < getRows(); x++) {
cout << "|";
for (unsigned y = 0; y < getCols(); y++) {
cout << setw(colWidth) << at(x, y) << " |";
}
cout << endl;
}
cout << "-";
for (unsigned int d = 0; d < getCols(); d++) {
cout << "--------";
}
cout << endl;
}
But the output depends on the colWidth which will be the space between each number printed. So how can I adjust my dashes to be printed like the following no matter the colWidth it should align.
One output should look like this:
Second output is like this:
If the column width is a parameter, you're almost done with your code. Just turn the cout<<"--------" into:
std::cout << std::string(getCols()*(colWidth + 2) + 1, '-');
That code prints a string of dashes, which width is: number of matrix columns, times column width plus 2, plus 1:
Plus 2 because you are appending a " |" to each column.
Plus 1 because you are adding a '|' at the beginning of each row.
You may want to check for empty matrices at the beginning of your print method.
[Demo]
#include <initializer_list>
#include <iomanip> // setw
#include <iostream> // cout
#include <vector>
class matrix
{
public:
matrix(std::initializer_list<std::vector<int>> l) : v{l} {}
size_t getRows() const { return v.size(); }
size_t getCols() const { if (v.size()) { return v[0].size(); } return 0; }
int at(size_t x, size_t y) const { return v.at(x).at(y); }
void print(int colWidth) const
{
std::cout << "Matrix: " << getRows() << " x " << getCols() << "\n";
// +2 due to " |", +1 due to initial '|'
std::cout << std::string(getCols()*(colWidth + 2) + 1, '-') << "\n";
for (unsigned x = 0; x < getRows(); x++) {
std::cout << "|";
for (unsigned y = 0; y < getCols(); y++) {
std::cout << std::setw(colWidth) << at(x, y) << " |";
}
std::cout << "\n";
}
std::cout << std::string(getCols()*(colWidth + 2) + 1, '-') << "\n";
}
private:
std::vector<std::vector<int>> v{};
};
int main()
{
matrix m{{1, 2}, {-8'000, 100'000}, {400, 500}};
m.print(10);
}
// Outputs
//
// Matrix: 3 x 2
// -------------------------
// | 1 | 2 |
// | -8000 | 100000 |
// | 400 | 500 |
// -------------------------

Why is this ranged based for loop causing issues with subtraction?

I'm having an issue with a ranged based for loop causing my values to go negative, and I've resolved the issue with a regular for loop but want to understand why it messed up in the first place. You can see from the sample output below that the initial values exist correctly, but then when attempting to subtract from them, they get reset to a default initialized value of 0 I guess?
Broken code:
#include <iostream>
#include <vector>
#define IS_TRUE(x) { if (!(x)) std::cout << __FUNCTION__ << " failed on line " << __LINE__ << std::endl; }
int maximumScore(std::vector<int>& nums, std::vector<int>& multipliers) {
std::vector<int> multRank;
multRank.resize(multipliers.size());
std::cout << "multRank: ";
//ISSUE IS IN THE LOOP BELOW
for (int n : multRank) {
n = multipliers.size();
std::cout << " " << n;
}
std::cout << std::endl;
for (auto i = 0; i < multipliers.size(); ++i) {
for (auto j = 0; j < multipliers.size(); ++j) {
int abs1 = std::abs(multipliers[i]);
int abs2 = std::abs(multipliers[j]);
if (abs1 > abs2) {
multRank[i] = multRank[i] - 1;
std::cout << multRank[i];
}
}
}
std::cout << std::endl << "multRank after: ";
for (int n : multRank) {
std::cout << " " << n;
}
std::cout << std::endl << std::endl;
return 0;
}
void test1()
{
std::vector<int> nums = { 1, 2, 3 };
std::vector<int> multipliers = { 3, 2, 1 };
int test = maximumScore(nums, multipliers);
IS_TRUE(test == 14);
}
int main()
{
std::cout << "Maximum Score from Performing Multiplication Operations\n";
test1();
}
Broken code output:
Maximum Score from Performing Multiplication Operations
multRank: 3 3 3
-1-2-1
multRank after: -2 -1 0
Repaired code:
#include <iostream>
#include <vector>
#define IS_TRUE(x) { if (!(x)) std::cout << __FUNCTION__ << " failed on line " << __LINE__ << std::endl; }
int maximumScore(std::vector<int>& nums, std::vector<int>& multipliers) {
std::vector<int> multRank;
multRank.resize(multipliers.size());
std::cout << "multRank: ";
//ISSUE WAS IN THE LOOP BELOW
for (auto i = 0; i < multipliers.size(); ++i) {
multRank[i] = multipliers.size();
std::cout << " " << multRank[i];
}
std::cout << std::endl;
for (auto i = 0; i < multipliers.size(); ++i) {
for (auto j = 0; j < multipliers.size(); ++j) {
int abs1 = std::abs(multipliers[i]);
int abs2 = std::abs(multipliers[j]);
if (abs1 > abs2) {
multRank[i]--;
std::cout << multRank[i];
}
}
}
std::cout << std::endl << "multRank after: ";
for (int n : multRank) {
std::cout << " " << n;
}
std::cout << std::endl << std::endl;
return 0;
}
void test1()
{
std::vector<int> nums = { 1, 2, 3 };
std::vector<int> multipliers = { 3, 2, 1 };
int test = maximumScore(nums, multipliers);
IS_TRUE(test == 14);
}
int main()
{
std::cout << "Calculate Rank\n";
test1();
}
Repaired code output:
Maximum Score from Performing Multiplication Operations
multRank: 3 3 3
212
multRank after: 1 2 3
The first range based for loop is not using references:
for (int n : multRank) {
n = multipliers.size();
std::cout << " " << n;
}
In this loop, n is a copy of the data in multRank. If you want to be able to modify the data in multRank, you want n to be a reference:
for (int& n : multRank) {
n = multipliers.size();
std::cout << " " << n;
}

returning multiple values in value returning function

I want to write a program that counts the number of times a certain vowel appears in a string but each value must be returned.
int vowel_count(string);
int main()
{
string str;
cout << "Enter a string";
cin >> str;
// Calling funtion:
vowel_count(str);
}
int vowel_count(string var)
{
int sum_a = 0;
int sum_e = 0;
int sum_i = 0;
int sum_o = 0;
int sum_u = 0;
for (int j = 0; j < var.length(); j++)
{
if (Var.at(j) == 'a')
sum_a++;
if (Var.at(j) == 'e')
sum_e++;
if (Var.at(j) == 'i')
sum_i++;
if (Var.at(j) == 'o')
sum_o++;
if (Var.at(j) == 'u')
sum_u++;
}
return sum_a;
return sum_e;
return sum_i;
return sum_o;
return sum_u;
}
Everytime I return , the program terminates, I would like to know how to I overrun the function of return.
You can use std::tuple to return multiple values from a function. Then you can either use std::get or std::tie to get at the values in the tuple. This avoids having to define a struct/class simply for the purpose of returning a result from your function vowel_count().
Since you tagged your question with C++14, I assume you haven't got C++17. However, with C++17 you can use structured bindings to extract the values instead.
For C++11/C++14:
#include<iostream>
#include<tuple>
using TupleVowel = std::tuple<int, int, int, int, int>;
TupleVowel vowel_count(std::string var)
{
int sum_a = 0;
int sum_e = 0;
int sum_i = 0;
int sum_o = 0;
int sum_u = 0;
for (int j = 0; j < var.length(); j++)
{
if (var.at(j) == 'a')
sum_a++;
if (var.at(j) == 'e')
sum_e++;
if (var.at(j) == 'i')
sum_i++;
if (var.at(j) == 'o')
sum_o++;
if (var.at(j) == 'u')
sum_u++;
}
return std::make_tuple(sum_a, sum_e, sum_i, sum_o, sum_u);
}
int main(void)
{
int sum_a = 0;
int sum_e = 0;
int sum_i = 0;
int sum_o = 0;
int sum_u = 0;
std::tie(sum_a, sum_e, sum_i, sum_o, sum_u) = vowel_count("hello world");
std::cout << "sum_a = " << sum_a << ", sum_e = " << sum_e << ", sum_i = " << sum_i << ", sum_o = " << sum_o << ", sum_u = " << sum_u << std::endl;
}
Live demo.
You can also use std::get() with the index of the element like this without having to 'tie' the tuple elements to variables:
auto tup = vowel_count("hello world");
std::cout << "sum_a = " << std::get<0>(tup) << ", sum_e = " << std::get<1>(tup) << ", sum_i = " << std::get<2>(tup) << ", sum_o = " << std::get<3>(tup) << ", sum_u = " << std::get<4>(tup) << std::endl;
In C++17, you can just do:
auto [sum_a, sum_e, sum_i, sum_o, sum_u] = vowel_count("hello world");
Live demo.
When the type of the returned variable is the same, you can use a std::array (also std::vector or std::deque, but, given that the number of the returned variable is fixed, I suppose std::array is preferable)
I mean, something as follows
#include <array>
#include <iostream>
auto vowel_count (std::string var)
{
int sum_a = 0;
int sum_e = 0;
int sum_i = 0;
int sum_o = 0;
int sum_u = 0;
for ( auto const & ch : var )
if ( ch == 'a') ++sum_a;
else if ( ch == 'e') ++sum_e;
else if ( ch == 'i') ++sum_i;
else if ( ch == 'o') ++sum_o;
else if ( ch == 'u') ++sum_u;
return std::array<int, 5u>{ sum_a, sum_e, sum_i, sum_o, sum_u };
}
int main()
{
std::string str;
std::cout << "Enter a string";
std::cin >> str;
auto vc = vowel_count(str);
std::cout << "a: " << vc[0] << std::endl;
std::cout << "e: " << vc[1] << std::endl;
std::cout << "i: " << vc[2] << std::endl;
std::cout << "o: " << vc[3] << std::endl;
std::cout << "u: " << vc[4] << std::endl;
}
Observe that, starting from C++17, you can use structured bindings, exactly as suggested from jignatius in the std::tuple based solution.
auto [sum_a, sum_e, sum_i, sum_o, sum_u] = vowel_count(str);
std::cout << "a: " << sum_a << std::endl;
std::cout << "e: " << sum_e << std::endl;
std::cout << "i: " << sum_i << std::endl;
std::cout << "o: " << sum_o << std::endl;
std::cout << "u: " << sum_u << std::endl;
The answers above are way too complicated.
The easiest solution is a simple struct.
struct VowelResult {
int a;
int e;
int i;
int o;
int u;
};
VowelResult func () {
int sumA = 0;
int sumE = 0;
int sumI = 0;
int sumO = 0;
int sumU = 0;
//your code goes here...
return {sumA,sumE,sumI,sumO,sumU}; // order matters here
// alternatively:
// VowelResult res{};
// res.a = sumA;
// res.e = sumE;
// and so on...
// return res;
// alternatively alternativey you can simply use the struct directly to store the sums
}

C++ linker undefined reference to function cannot find my error

It is a homework problem. It compiles fine, but linker gives undefined reference to my function getSalesData - line 20 just after my first for loop. Here is the code. I cannot find where I have done anything incorrectly; I have my prototype defined and it matches my function header, and I am simply calling the function.
// chips and salsa
#include <iostream>
#include <iomanip>
#include <string>
int getJarsSold(std::string type);
void getSalesData(int jarsSold[],int size,int &totalJars,int &highSeller,int &lowSeller);
int main() {
const int SIZE = 5;
const std::string salsaTypes[] {"Mild","Medium","Sweet","Hot","Zesty"};
int jarsSold[SIZE] = {};
int highIndex,lowIndex,totalJarsSold;
for (int i = 0; i < SIZE; i++) {
jarsSold[i] = getJarsSold(salsaTypes[i]);
}
getSalesData(jarsSold,SIZE,totalJarsSold,highIndex,lowIndex);
std::cout << " Type Jars Sold\n";
std::cout << "---------------------\n";
for (int i = 0; i < SIZE; i++) {
std::cout << std::setw(8) << salsaTypes[i] << std::setw(15) << jarsSold[i] << std::endl;
}
std::cout << "*********************\n";
std::cout << "Total Sales = " << totalJarsSold << std::endl;
std::cout << "Highest Seller = " << salsaTypes[highIndex] << std::endl;
std::cout << "Lowest Seller = " << salsaTypes[lowIndex] << std::endl;
}
int getJarsSold(std::string type) {
bool validData = false;
int numJars;
while (!validData) {
std::cout << "Enter jars sold this month for " << type << " salsa type: ";
std::cin >> numJars;
if (numJars < 0) {
std::cout << "Number of jars sold must be 0 or positive number.\n";
}
else {
validData = true;
}
}
validData = false;
return numJars;
}
void getSalesData(int jarsSold[],int size,int totalJars,int highIndex,int lowIndex) {
bool firstRun = true;
int highVal,lowVal;
totalJars = 0;
for (int i = 0; i < size; i++) {
if (firstRun) {
highIndex = i;
highVal = jarsSold[highIndex];
lowIndex = i;
lowVal = jarsSold[lowIndex];
totalJars += jarsSold[i];
firstRun = false;
}
else {
totalJars += jarsSold[i];
if (jarsSold[i] > highVal) {
highVal = jarsSold[i];
highIndex = i;
}
if (jarsSold[i] < lowVal) {
lowVal = jarsSold[i];
lowIndex = i;
}
}
}
}
Any help is appreciated. I am just using -c for compiling and -o for linking, nothing fancy as I know no better.

Which are the best methods for speeding up the algorithm based on vector search?

I am trying to solve the Euler question 419
So far, I think I managed to build an algorithm to find the answer. Or at least it gives the correct result for first 40 step. But I need to compute 1,000,000,000,000th step. Solving first 40 step (with my algorithm) takes about 3-4 seconds. And bigger the iteration number increases, computation time increases as well. I don't think my computer can solve 1,000,000,000,000 iteration in a year.
What I do is simply using temporary vectors for both sequential number counting(form_1 and form_2) and keeping the calculated the result for each iteration(testVec). Here is my code below:
#include <iostream>
#include <stdio.h>
#include <vector>
#include <cmath>
std::vector<int> form_1;
std::vector<int> form_2;
std::vector<int> testVec;
void showVec(std::vector<int>& vec)
{
//
for (unsigned long int i = 0; i < vec.size(); i++)
{
//
std::cout << vec[i] << std::endl;
}
}
void resFin(int start, int stop, std::vector<int>& vec)
{
//
for (unsigned long int i = 0; i < vec.size(); i++)
{
//
if (i == 0)
{
//
form_1.push_back(vec[0]);
//std::cout << "form_1 pushed " << vec[0] << std::endl;
}
else
{
//
if (i != vec.size() - 1)
{
//
if (vec[i] == vec[i - 1])
{
//
form_1.push_back(vec[i]);
//std::cout << "form_1 pushed " << vec[i] << std::endl;
}
else
{
//
form_2.push_back(form_1.size());
form_2.push_back(vec[i - 1]);
form_1.clear();
form_1.push_back(vec[i]);
}
}
else
{
//
if (vec[i] == vec[i - 1])
{
//
form_1.push_back(vec[i]);
//std::cout << "form_1 pushed " << vec[i] << std::endl;
form_2.push_back(form_1.size());
//std::cout << "form_2 pushed " << form_1.size() << std::endl;
form_2.push_back(vec[i - 1]);
//std::cout << "form_2 pushed " << vec[i - 1] << std::endl;
form_1.clear();
}
else
{
//
form_2.push_back(form_1.size());
//std::cout << "form_2 pushed " << form_1.size() << std::endl;
form_2.push_back(vec[i - 1]);
//std::cout << "form_2 pushed " << vec[i - 1] << std::endl;
form_2.push_back(1);
//std::cout << "form_2 pushed " << 1 << std::endl;
form_2.push_back(vec[i]);
//std::cout << "form_2 pushed " << vec[i] << std::endl;
form_1.clear();
}
}
}
}
vec.clear();
for (unsigned long int k = 0; k < form_2.size(); k++)
{
//
vec.push_back(form_2[k]);
//std::cout << "vec pushed " << form_2[k] << std::endl;
}
//showVec(vec);
if (start + 1 != stop)
{
//
form_1.clear();
form_2.clear();
std::cout << "recursed to " << start + 1 << std::endl;
resFin(start + 1, stop, vec);
}
}
void stepFind(int stop, std::vector<int>& vec)
{
//
resFin(1, stop, vec);
}
void trimmVec(std::vector<int>& vec)
{
//
int a = 0;
int b = 0;
int c = 0;
for (unsigned long int i = 0; i < vec.size(); i ++)
{
//
switch (vec[i])
{
case 1:
a++;
a = a % 1073741824;
break;
case 2:
b++;
b = b % 1073741824;
break;
case 3:
c++;
c = c % 1073741824;
break;
default:
break;
}
}
std::cout << "a is " << a << "; b is " << b << "; c is " << c << std::endl;
}
int main()
{
//
testVec.push_back(1);
testVec.push_back(1);
stepFind(39, testVec);
//showVec(testVec);
trimmVec(testVec);
getchar();
return 0;
}
I think no one ought to wait more than a few hours to solve euler problems right? So I am doing something wrong here. So, are there such methods existed to minimize computing time, especially in vectors inside searching(I think this consumes the time most)?