c++ std::cout unespected output - c++

Hi I'm writing some debug output with std::cout with this code:
EDIT: as suggested I added a std::flush on each cout and an std::endl on each iteration
int
index = 0,
size = vector.size();
for (iterate trough a vector)
{
std::cout << "Actual element: " << index+1 << "/" << size << std::flush;
...
if (bad element)
{
std::cout << " -> Bad Element" << std::flush;
}
std::cout << std::endl;
}
The bad element string appear only after the successive element, why?
What am I missing?
Thanks a lot!

You should have a std::cout << std::flush (or std::cout << std::endl) in your for loop which is always done (even without bad elements), or at least after your for loop....

Related

output to screen terminates when I try to access array in C++ [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 12 months ago.
I'm trying to return a pointer, that points to an array of strings, from a function and then access elements in the array that the returned pointer points to. I seem to get a pointer back from the function, but when I try to output individual elements of the array to the computer screen, my program seems to just stop outputting and end the program.
Running the code below, the pointer to the array outputs as expected (see screen output screenshot). However, when I try to access the array's elements, none of the elements are output to the screen and the program just ends. Any ideas/thoughts would be greatly appreciated. FYI, I realize that I'm not using the data that's being passed to the function, but that's because I'm trying to figure out how to access the data that gets returned first.
roster.h
#ifndef ROSTER_H
#define ROSTER_H
#include <iostream>
#include <string>
class Roster {
public:
std::string* parseData(const std::string Data);
};
#endif
roster.cpp
#include <iostream>
#include <string>
#include "roster.h"
std::string* Roster::parseData(const std::string Data) {
std::string stringData[3] = { "abc", "def", "ghi" };
return stringData;
}
rostertest.cpp
#include <iostream>
#include <string>
#include "roster.h"
void rosterClassTest()
{
Roster roster;
std::string* returnData = roster.parseData("red,blue,black,gray");
std::cout << "pointer returned: "
<< returnData << std::endl << std::endl;
std::cout << "element 0 of array: "
<< returnData[0] << std::endl << std::endl;
std::cout << "element 1 of array: "
<< returnData[1] << std::endl << std::endl;
std::cout << "element 2 of array: "
<< returnData[2] << std::endl << std::endl;
}
Roster::parseData() is returning a pointer to a local array variable that goes out of scope upon exit, destroying the array, and thus the function is returning a dangling pointer to invalid memory.
You should return a std::vector<std::string> (or std::array<std::string, 3>) instead, eg:
std::vector<std::string> Roster::parseData(const std::string Data) {
std::vector<std::string> stringData{ "abc", "def", "ghi" };
return stringData;
}
std::vector<std::string> returnData = roster.parseData("red,blue,black,gray");
std::cout << "pointer returned: " << returnData.data() << std::endl << std::endl;
for(size_t i = 0; i < returnData.size(); ++i) {
std::cout << "element " << i << " of array: " << returnData[i] << std::endl << std::endl;
}
If that is not an option, then you will have to new[] the array, and then the caller will have to delete[] the array when finished using it, eg:
std::string* Roster::parseData(const std::string Data) {
std::string *stringData = new std::string[3];
stringData[0] = "abc";
stringData[1] = "def";
stringData[2] = "ghi";
return stringData;
}
std::string* returnData = roster.parseData("red,blue,black,gray");
std::cout << "pointer returned: " << returnData << std::endl << std::endl;
std::cout << "element 0 of array: " << returnData[0] << std::endl << std::endl;
std::cout << "element 1 of array: " << returnData[1] << std::endl << std::endl;
std::cout << "element 2 of array: " << returnData[2] << std::endl << std::endl;
delete[] returnData;
In which case, you should return a std::unique_ptr instead, eg:
std::unique_ptr<std::string[]> Roster::parseData(const std::string Data) {
//std::unique_ptr<std::string[]> stringData(new std::string[3]);
auto stringData = std::make_unique<std::string[]>(3);
stringData[0] = "abc";
stringData[1] = "def";
stringData[2] = "ghi";
return stringData;
}
auto returnData = roster.parseData("red,blue,black,gray");
std::cout << "pointer returned: " << returnData.get() << std::endl << std::endl;
std::cout << "element 0 of array: " << returnData[0] << std::endl << std::endl;
std::cout << "element 1 of array: " << returnData[1] << std::endl << std::endl;
std::cout << "element 2 of array: " << returnData[2] << std::endl << std::endl;

Using stringstream's ignore

I am trying to use a stringstream as a buffer but I am unable to update the underlying streambuf :
#include <iostream>
#include <sstream>
int main () {
std::stringstream ss(std::ios_base::app|std::ios_base::in|std::ios_base::out); //ostringstream gives the same output
ss << "foo";
std::cout << "position get: " << ss.tellg() << std::endl;
std::cout << "position put: " << ss.tellp() << std::endl;
ss << "b";
std::cout << "position get: " << ss.tellg() << std::endl;
std::cout << "position put: " << ss.tellp() << std::endl;
char c;
ss >> c;
std::cout << "position get: " << ss.tellg() << std::endl;
std::cout << "position put: " << ss.tellp() << std::endl;
ss.ignore(1);
std::cout << "position get: " << ss.tellg() << std::endl;
std::cout << "position put: " << ss.tellp() << std::endl;
std::cout << ss.str() << std::endl;
return 0;
}
yields:
position get: 0
position put: 3
position get: 0
position put: 4
position get: 1
position put: 4
position get: 2
position put: 4
foob
Is it possible to force a reallocation of the streambuf underlying object ? If not, is this reallocation automatic and in which circumstance is it triggered ?
I know I can use ss.str to change the underlying buffer. But it is a pain to use it to manually update the buffer to a substr's version.
Note: I am doing a school project and must compile to c++98, hence, if you have a solution which is comptabible, it would be much appreciated.

How can I remove values from output statement given a condition? - c++

I'm a little confused as to how to go around this. I have some array variables with some information, and I want to print them out after some calculations. If the value is 0, then I want to print a " " instead. There are 3 arrays that need to get checked however, how would I change the output statement to cater for all 3 checks and print an empty string instead of the value?
for(int start = 1; start < 13; start++)
{
if(check[start] == 1)
{
cout << checkMonth(start) << ": " << setprecision(1) << fixed << averagespeed[start] << "(" << setprecision(1) << fixed << sdSpeed[start] << ")," << setprecision(1) << fixed << averagetemp[start] << "(" << setprecision(1) << fixed << sdTemp[start] << ")," << setprecision(1) << fixed << Solar[start] << '\n';
}
/*if(sumTemp[start] == 0 || sumTemp[start] == 0 || sumSpeed[start] == 0){
}*/
}
Example Output looks like this:
January,5.5(1.2),25.5(12.2),196.4
For example if Sum of Speed is 0, that means all values of speed were 0 or null. So it should change to this:
January,,25.5(12.2),196.4
A single line to std::cout doesn't need to be done in one statement. For example:
std::cout << "First";
std::cout << ", second"
std::cout << ", third\n"
Prints the following line:
First, second, third
Now we can use an if to conditionally print the middle part of the string:
std::cout << a;
if (b != 0) {
std::cout << ", " << b;
}
std::cout << ", " << c << '\n';

How to decrease a size of a specific bucket in unordered_set by one?

I am using std::unordered_set to count how many different numbers do I have in my array.
What I am trying to do is to decrease a size of a specific bucket by one when one of the occurrences of a number is being deleted from my array.
I tried using erase(), but that removes the whole bucket. Is there any possibility to do it somehow?
It should work like this:
std::unordered_set<int> P;
P.insert(0);
P.insert(0);
printf("%d", P.count(0)); //this prints 2
//P.decrease(0) <-- I'm looking for something like this
printf("%d", P.count(0)); //this should print 1
You can't have a count with set. Everything is either in the set, or not in the set. Perhaps you want to use a map? I just wrote some sample code to demonstrate the difference.
#include <unordered_set>
#include <unordered_map>
#include <iostream>
int main() {
// http://en.cppreference.com/w/cpp/container/unordered_set
std::unordered_set<int> s;
std::cout << "Things are either in the set, or not in the set. There is no count." << std::endl;
std::cout << "insert 0" << std::endl;
s.insert(0);
std::cout << "insert 0" << std::endl;
s.insert(0);
std::cout << "have we seen a 0, yes or no? " << s.count(0) << std::endl;
std::cout << "erase 0" << std::endl;
s.erase(0);
std::cout << "have we seen a 0, yes or no? " << s.count(0) << std::endl;
// http://en.cppreference.com/w/cpp/container/unordered_map
std::unordered_map<int, int> m;
std::cout << "Every key in the map has a value. We can use that to represent count." << std::endl;
std::cout << "add 1 to the count for value 0" << std::endl;
m[0] += 1;
std::cout << "add 1 to the count for value 0" << std::endl;
m[0] += 1;
std::cout << "How many zeroes are in the bucket? " << m[0] << std::endl;
std::cout << "subtract 1 from the count for key==0" << std::endl;
m[0] -= 1;
std::cout << "How many zeroes are in the bucket? " << m[0] << std::endl;
}

get the rank of an element of a boost::multi_index container

The code below shows a multi_index container which is indexed by sequence and order.
In my use case elements will be mainly searched by index, and if existing, the next element (by order) is obtained.
My question is, how to get the rank (by order) of obtained next element?
#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/ranked_index.hpp>
#include <boost/multi_index/identity.hpp>
using namespace boost::multi_index;
typedef multi_index_container <
int
, indexed_by<
sequenced<>
, ordered_non_unique<identity<int>>
, ranked_non_unique<identity<int>>
>
> Ints;
int main() {
Ints ints;
auto & sequence=ints.get<0>();
auto & order=ints.get<1>();
sequence.push_back(2);
sequence.push_back(-1);
sequence.push_back(5);
sequence.push_back(6);
auto it = order.find(2);
if (it!=order.end()) {
std::cout
<< "next to "
<< *it
<< " by sequence is "
<< *(++(ints.project<0>(it)))
<< std::endl
;
std::cout
<< "next to "
<< *it
<< " by order is "
<< *(++(ints.project<1>(it))) //++it is good too
<< std::endl
;
std::cout
<< "rank of next by sequence is "
// << ??? ints.rank<???>(???)
<< std::endl
;
std::cout
<< "rank of next by order is "
// << ??? ints.rank<???>(???)
<< std::endl
;
}
}
#sehe's answer is perfectly valid but runs in linear time. If you want better performance, consider defining your index #0 as random_access and #1 as ranked_non_unique (index #2 is redundant):
typedef multi_index_container <
int
, indexed_by<
random_access<>
, ranked_non_unique<identity<int>>
>
> Ints;
so that you can write:
std::cout
<< "rank of next by sequence is "
<< ints.project<0>(it)-sequence.begin()+1 // O(1)
<< std::endl
;
std::cout
<< "rank of next by order is "
<< order.rank(it)+1 // O(log n)
<< std::endl
;
Assuming you want some kind of "index into" or "offset from begin" in the sequenced index:
if (it!=order.end()) {
auto rank_of = [&](auto it) {
return std::distance(sequence.begin(), ints.project<0>(it));
};
auto seq_next = std::next(seq_it);
auto ord_next = std::next(it);
if (seq_next!=sequence.end())
{
std::cout << "next to " << *it << " by sequence is " << *seq_next << std::endl;
std::cout << "rank of next by sequence is " << rank_of(seq_next) << std::endl;
}
if (ord_next!=order.end())
{
std::cout << "next to " << *it << " by order is " << *ord_next << std::endl ;
std::cout << "rank of next by order is " << rank_of(ord_next) << std::endl;
}
}
Without polymorphic lambdas you should write it out