I am pretty sure all of you are familiar with the concept of the Big4, and I have several stuffs to do print in each of the constructor, assignment, destructor, and copy constructor.
The restriction is this:
I CAN'T use more than one newline (e.g., ƒn or std::endl) in any method
I can have a method called print, so I am guessing print is where I will put that precious one and only '\n', my problem is that how can the method print which prints different things on each of the element I want to print in each of the Big4? Any idea? Maybe overloading the Big4?
Maybe I don't understand the question completely because it is asked rather awkwardly, but can't you just have a function called newline that receives an ostream as an argument, and then simply prints '/n' to that output stream? Then you can just call that infinitely many times, while still abiding the arbitrary "one newline" rule.
e.g.
(edit: code removed, "smells like homework")
print should take a parameter containing the information to output to the screen (sans '\n') and then call the c++ output method with in-line appending the '\n' to the passed in information.
note: no code 'cause this smells like homework to me...
I'm not sure I completely understand what you're trying to accomplish. Why is it that you can only use one newline? What makes it difficult to just write your code with only one newline in it? For example, I've done stuff like this before.
for(int i = 0; i < 10; i++) {
cout << i << " ";
}
cout << std::endl;
If you need something more complicated, you might want to make some sort of print tracker object that keeps a flag for whether a newline has been printed, and adjusts its behavior accordingly. This seems like it might be a little overly complicated though.
Related
I was wondering if in code such as this:
std::cout << "Hello!" << '\n';
Would it be more efficient to have the \n character in the same string literal, as in this case, "Hello!"? Such as the code would then look like this:
std::cout << "Hello!\n";
I am aware that things such as these are so miniscule in difference whether one is more efficient than the other (especially in this case), that it just doesn't matter, but it has just been boggling my mind.
My reasoning:
If I am not mistaken having the \n character in the same string literal would be more efficient, since when you have the extra set of the insertion operator (operator<<) you have to call that function once again and whatever is in the implementation of that function, which in this case, in the Standard Library, will happen just for one single character (\n). In comparison to only having to do it once, that is, if I were to append that character to the end of the string literal and only have to use one call to operator<<.
I guess this is a very simple question but I am not 100% sure about the answer and I love to spend time knowing the details of a language and how little things work better than others.
Update:
I am working to find the answer myself as for questions such as this, it is better for one to try and find the answer for themselves, I haven't worked with any Assembly Code in the past, so this will be my firs time trying to.
Yes; but all of the ostreams are so inefficient in practice that if you care much about efficiency you shouldn't be using them.
Write code to be clear and maintainable. Making code faster takes work, and the simpler and clearer your code is the easier to make it faster.
Identify what your bottleneck is, then work on optimizing that by actually working out what is taking time. (This only fails when global behaviour caused global slowdowns, like fragmentation or messing with caches because).
std::istream & Date::read(std::istream & istr)
{
char* buffer = nullptr;
const bool ISTREAM_IS_OKAY = !(istr.fail());//okay if it didn't fail
if (ISTREAM_IS_OKAY)
{
cout << "Enter a string: ";
const int SIZE = 256;
buffer = new char[SIZE];
istr.getline(buffer, SIZE);
cout << "\n" << buffer << " " << strlen(buffer) << endl;
istr.getline(buffer, SIZE, '/');
cout << "\n" << buffer << " " << strlen(buffer) << endl;
istr.getline(buffer, SIZE, '/');
cout << "\n" << buffer << " " << strlen(buffer) << endl;
}
else
{//CIN_FAILED is a pre-processor directive which is equal to 1
m_readErrorCode = CIN_FAILED; //m_readErrorCode is just an int
}
delete[] buffer;
return istr;
}
I am trying to read in a date in one string using cin.getline(). Dependent upon whether the boolean member variable m_dateOnly is true or false, the date is to be printed in one of the following two fashions:
1) if(m_dateOnly==true)....
2017/3/18
2) else...print the date and time
2017/3/18 , 12:36
I'm aware that the logic in my code does not entirely dictate what I just explained(It's still a WIP). I came to a halt because when I enter the following:
"abcd" ... no delimiter here
cin.getline() continues to run until the user enters a string with the given delimiter in it.
How can I get cin.getline() to stop on the first instance of an invalid string as opposed to it continuously running?
Note: I am required to use the istream passed as an argument
Thanks in advance!
Basically you can't, because getline will not stop until it encounters the terminator it expects, the buffer gets full or the input ends.
At any rate, you can't pass it a list of 2 characters or more (the expected terminator and/or some illegal characters) it should stop on.
If you really want your code to react on a character per character basis, you will need to use character by character input, with methods like sgetc or sbumpc.
I would not advise to do so, because that would force you to handle all the pesky edge cases like your input buffer getting full of the input being terminated, which getline can handle without headache.
You could also use the >> operator to grab bits of characters or numbers according to whatever format is expected for your date and time. Trouble is, that would force you to check the state of your input stream after each >> invokation, making for ponderous and nigh unreadable code.
Another possibility is to use scanf like functions, but they have the slight downside of including an undefined behaviour on numeric inputs, meaning typing a large number of digits when it expects a number could theoretically lead to a program crash, a random memory corruption or your mustache turning pink.
Yet another possibility is to piss a couple dozen lines of code to create your own homemade list of separators through the imbue method and a custom ctype object. I would not touch that with a 10 feet pole, but I'm sure a lot of senior developpers pull that trick to impress the chicks...
Now if you ask me, C++ string I/O is an appallingly awkward leftover from the 90's: no regular expressions, no garbage collection, no associative memory, so you will end up checking the characters you just read, monitoring the state of your I/O stream and allocating bits of buffers every second line of code. You're bound to suffer one way or another. I would just not make it more painful than it has to be, if I were you.
The usual way of circumventing the crappy C++ I/O is to read a plain line (terminated by a good old \n, usually what you get when you hit the enter key), and then analyze the resulting string buffer by hand. Once you're done with reading an actual input, you don't have to worry about buffers overflowing or input terminating at an awkward moment. That usually makes things a lot less messy.
btw. my personal preference goes to never having to call delete on a null pointer. You can do it, but that makes for pretty dangerous code that tends to break if you modify it one time too many. It could arguably save you a few minutes of coding, but might also cost you (or one of your infortunate coworkers) a few hours of debugging a few weeks/months later.
If your buffer is only used within a code block, better make it a local variable that will be cleaned up automatically. Use dynamic allocation only when you really need it.
No doubt a lot of C++ zealots will be eager to explain the contrary, but this bit of wisdom comes from long nights spent munching pizzas in front of buggy code, often written by people who were just a bit too smart for their own good (and the good of their coworkers, incidentally). Make what you want of it, it comes free of charge.
I try to track down an error in a R-script that does call a C++ program. The R tells me, that my C++ returned NA - but that does not seems to be the case when I look through the program. There is nothing called that would result in NA in R. Hence my question, if R may never capture the output from the C++ program, because return 0 is called before all output has been written to the console.
My program does writes some numbers to the console. One number per line, the last line ends with endl.
main()
{
cout<<33.12<<"\n"; //print a couple of number to cout
cout<<9711.3<<"\n"<<5699.14<<endl;
return 0;
}
My R-Script does stuff like this:
x <- as.numeric(system("./myProgram", intern=T))
if(any(is.na(x))) {
stop("Wooppp, x is NA: ", x)
}
Can it be, that R does not get the cout-output from by program?
This question is related to the corresponding R-question:
DEOptim keeps telling: NaN value of objective function
In general, yes, it would be possible to have part of the output not yet flushed before the end of main(). However, by the end of the program, everything should be flushed anyhow.
Some more detail, main is just a function, for the programmer this is the entry point of the program, though actually the runtime does some parts before/after this call. This includes loading shared objects, calling destructors of global variables and some other stuff you actually shouldn't know anything about as a regular programmer.
As std::cout is a global object, it will use its destructor to flush the right data. Though as most implementations flush on the "\n" character (don't think it is needed), std::endl and std::flush (I thought this was required), this example should be fine anyhow.
I would try splitting this issue, and try pushing the output of the C++ program to file to read it afterwards (both from the same R-program), try console input ...
I have written a simple recursive descent parser in C++.
I need a way to print it to std out but I cannot figure out how to do this.
I have a class Node and it has a function printSymbol() to print its symbol.
It has a std::list <Node*> m_children for its children.
Given this, how can I pretty print the parse tree to std out?
Thanks
Add an overload to printSymbol that takes an indent-level, or a default value, either works:
void printSymbol(unsigned indent = 0) const
{
std::cout << std::string(indent,' ') << m_symbol << '\n';
for (auto child : m_children)
child->printSymbol(indent+2);
}
Given any single node a direct call to printSymbol() should simply output the symbol, a newline, and all its children if it has any, all properly indented. Given a root pointer this should dump your entire parse hierarchy to stdout. You can get extraordinarily creative regarding ascii art, console-dependent line chars if you're really set on it, but it can get tedious quickly, I warn you.
Regardless, this should at least give you a picture you can print. Either that or I utterly misunderstood your question.
Best of luck
I have an istream (ifstream, in this case), and I want to write a specific number of characters from it into an ostream (cout, to be specific).
I can see that this is possible using something like istream.get(), but that will create an intermediate buffer, which is something I'd prefer to avoid.
Something like:
size_t numCharacters = 8;
ostream.get(istream, numCharacters);
Can someone point me in the right direction?
Thanks for reading :)
Edit: added c++ tag
Edit: fixed title :/
New Edit:
Thanks very much for the answers guys. As a side note, can anyone explain this weird behaviour of copy_n? Basically it seems to not consume the last element copied from the input stream, even though that element appears in the output stream. The code below should illustrate:
string test = "testing the weird behaviour of copy_n";
stringstream testStream(test);
istreambuf_iterator<char> inIter( testStream );
ostream_iterator<char> outIter( cout );
std::copy_n(inIter, 5, outIter);
char c[10];
testStream.get(c,10);
cout << c;
The output I get is:
testiing the w
The output I would expect is:
testing the we
Nothing in the docs at cppreference.com mentions this kind of behaviour. Any further help would be much appreciated :)
My workaround for the moment is to seek 1 extra element after the copy - but that's obviously not ideal.
You won't be able to avoid copying the bytes if you want to limit the number of characters and you want to be efficient. For a slow version without a buffer you can use std::copy_n():
std::copy_n(std::istreambuf_iterator<char>(in),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(out),
n);
I'd be pretty sure that this is quite a bit slower than reading a buffer or a sequence thereof and writing the buffer (BTW make sure to call std::ios_base::sync_with_stdio(false) as it is otherwise likely to be really slow to do anything with std::cout).
You could also create a filtering stream buffer, i.e., a class derived from std::streambuf using another stream buffer as its source of data. The filter would indicate after n characters that ther are no more characters. It would internally still use buffers as individual processing of characters is slow. It could then be used as:
limitbuf buf(in, n);
out << &buf;