Evaluation order of expressions with read-line in Clojure [duplicate] - clojure

This question already has answers here:
Clojure - Side Effects Happening Out Of Order
(2 answers)
Closed 8 years ago.
I am running the following code snippet:
(print "Enter something:")
(let [entry (read-line)]
(println "You entered" entry)
)
I expect to see the following type of interaction:
Enter something:abc
You entered abc
Instead, I see:
abc
Enter something:You entered abc
Why is user input requested first, even though the print comes first in the code? I tried Googling around, but from what I can tell, evaluation order should be what I would expect coming from a Java/Python background. Is this the expected behavior of the code?

Just pasting my comment over into a real answer.
Java flushes stdout on \n. You will need to forcibly flush the buffer if you want the output exactly (read consistently, as you have no control over it) as you have written it in your example, or you could add a \n using (println ...) or (print ... "\n").
See: Will Java's System.out.print() buffer forever until println()?

Related

Endless do while loop in C++ code? [duplicate]

This question already has answers here:
Using the scanf() function
(4 answers)
Closed 5 years ago.
char input[256];
do{
cout<<"..."; //prompt
scanf("%s",&input5); //user inputs string
if(strcmp(input5,"block")==0)
{} //if the user types block, then it finishes the loop and goes to the cout at the bottom
else if(strcmp(input5,"attack")==0)
{
cout<<"..."<<endl;
}
else if(strcmp(input5,"look")==0)
{
cout<<"..."
}
else
{
cout<<"..."<<endl;
}
}while(strcmp(input5,"block")!=0); //loop ends when block is typed
cout<<"...";
I am having issues with my do while loop. I am doing a project for school that involves a text adventure kind of game. The user is prompting how to respond to an attack. The desired command is "block", which will move the user on to the next sequence. When "block" is typed into the scanf, it endlessly loops and prints what is in the "else" condition. I don't see what the problem is and all feedback is appreciated.
I just tried your code and it works fine (though I removed the & in the scanf), and created 'input5' as a char array.
Though that aside, there's a few things that you might want to change. I'd stick to using 'cin' instead of scanf, as you're mixing C and C++. That would allow you to use a 'string' for 'input5', and compare them using the '==' operator, which is quite a bit cleaner. Maybe think of a more descriptive name than 'input5' too, as if you've got lots of 'inputX' variables then things will get messy.
Edit: I'd also refrain from "using namespace std;", as you might end up with naming collisions.
Most likely you don't need the & operator before input5 on the scanf line, because the things scanf expects for %s fields are already pointers/arrays. Although I don't see how input5 is declared, so I'm not sure if this is the (only) problem. You should have included that in the code snippet also.
EDIT: Just a note: It's not particularly elegant to mix C-style (scanf) and C++ style (cout) IO. You wouldn't have this problem with cin.
Obviously, the loop does not terminate because the string comparison does not return equality. And this must be because input5 does not contain the typed input (and for the same reason, the else clause is executed whatever the input).
As input5 is only modified by the scanf call, this must be the root of the evil. A simple debugging session would have revealed it immediately.
The reason is simple: you must pass scanf the address of the buffer, but you are actually passing the address of the address, and overwriting the value of the variable input5 (for which we don't have the declaration but can infer char* or const char*).
In a 32 bits environment, this could cause a crash by overwriting the stack. Under 64 bits, you'll need more typing to obtain it.

Why is the return value of a function not evaluated but the return value of a macro is?

A function to add one and one:
(defn one-plus-one [] (list + 1 1))
when called returns:
(#object[clojure.core$_PLUS_ 0x47fa7bd5 "clojure.core$_PLUS_#47fa7bd5"] 1 1)
The same function body wrapped in a macro:
(defmacro one-plus-one [] (list + 1 1))
when called returns:
2
Why does Clojure expect macros to return expressions that can be evaluated?
Edit
The answers to the possible duplicate question tells how a macro is different from a function. But does not answer the why. Metaphorically, I know that an object left from an altitude drops vertically to hit the ground. My question is why does it drop vertically?
Let's just start with one thing many people know so well they forget to think about it explicitly when explaining macros, which causes others to be confused when learning to think about macros:
-----------> macros are functions <-------------
They are very often used to take lists of things that look like code, and are very often expected to return lists that can actually be run as code.
The difference between a macro and a function is not what it does (fundamentally), but when it does it. macros run while the code is "loading" and the value they return is run when the program runs.
when you write it as a macro it does two steps:
run the function to produce a list
run that returned list as code to produce a value
when you write it as a function it does one step:
run the function to produce a list
Then it stops.
The return value is diferent because the macro version takes that extra step of running the returned value as code.
code is data ... data is code ... yay lisp!

What is the purpose of * in Fortran input/output

I am learning Fortran because well, yeah, thought I'd learn it. However, I've found utterly no information on what the purpose of * is in print, read, etc:
program main
print *, "Hello, world!"
end program main
What is the purpose of this *? I've done some research however I don't think I understand it properly, I don't want to carry on learning until I actually know the point of *.
From what I've managed to find I think that it's some sort of format specifier, however, I don't understand what that means and I have no idea if I'm even correct. All the tutorials I've found just tell me what to write to print to the console but not what * actually means.
You are correct in that it is a format specifier.
There's a page on Wikibooks to do with IO and that states:
The second * specifies the format the user wants the number read with
when talking about the read statement. This applies to the write and print statements too.
For fixed point reals: Fw.d; w is the total number of spaces alloted for the number, and d is the number of decimal places.
And the example they give is
REAL :: A
READ(*,'(F5.2)') A
which reads a real number with 2 digits before and after the decimal point. So if you were printing a real number you'd use:
PRINT '(F5.2)', A
to get the rounded output.
In your example you're just printing text so there's no special formatting to do. Also if you leave the format specifier as * it will apply the default formatting to reals etc.
The print statement does formatted output to a special place (which we assume is the screen). There are three available ways to specify the format used in this output. One of these, as in the question, is using *.
The * format specifier means that the formatted output will be so-called list-directed output. Conversely, for a read statement, it will be list-directed input. Now that the term has been introduced you will be able to find many other questions here: list-directed input/output has many potentially surprising consequences.
Generally, a format specification item says how to format an item in the input/output list. If we are writing out a real number we'd use a format item which may, say, state the precision of the output or whether it uses scientific notation.
As in the question, when writing out a character variable we may want to specify the width of the output field (so that there is blank padding, or partial output) or not. We could have
print '(A20)', "Hello, world!"
print '(A5)', "Hello, world!"
print '(A)', "Hello, world!"
which offers a selection of effects. [Using a literal character constant like '(A)' is one of the other ways of giving the format.]
But we couldn't have
print '(F12.5)', "Hello, world!" ! A numeric format for a character variable
as our format doesn't make sense with the output item.
List-directed output is different from the above cases. Instead, (quote here and later from the Fortran 2008 draft standard) this
allows data editing according to the type of the list item instead of by a format specification. It also allows data to be free-field, that is, separated by commas (or semicolons) or blanks.
The main effect, and why list-directed is such a convenience, is that no effort is required on the part of the programmer to craft a suitable format for the things to be sent out.
When an output list is processed under list-directed output and a real value appears it is as though the programmer gave a suitable format for that value. And the same for other types.
But the crucial thing here is "a suitable format". The end user doesn't get to say A5 or F12.5. Instead of that latter the compiler gets to choose "reasonable processor-dependent values" for widths, precisions and so on. [Leading to questions like "why so much white space?".] The constraints on the output are given in, for example, Fortran 2008 10.10.4.
So, in summary * is saying, print out the following things in a reasonable way. I won't complain how you choose to do this, even if you give me output like
5*0
1 2
rather than
0 0 0 0 0 1 2
and I certainly won't complain about having a leading space like
Hello, world!
rather than
Hello, world!
For, yes, with list-directed you will (except in cases beyond this answer) get an initial blank on the output:
Except for new records created by [a special case] or by continuation of delimited character sequences, each output record begins with a blank character.

Why two EOF needed as input? [duplicate]

This question already has an answer here:
Canonical vs. non-canonical terminal input
(1 answer)
Closed 7 years ago.
When I run the code below, I use three inputs (in Ubuntu terminal):
abc(Ctrl+D)(Ctrl+D)
abc(Ctrl+D)(Enter)(Ctrl+D)
abc(Enter)(Ctrl+D)
The code reacts well in all cases. My question is: why in 1) and 2) I need two EOF?
#include <iostream>
int main()
{
int character;
while((character=std::cin.get())!=EOF){}
std::cout << std::endl << character << std::endl;
}
You don't have "two EOF". Bash is putting the tty in raw mode, and interpreting ^D differently depending on context. If you type ^D after a newline, bash closes the input stream on the foreground process. If you type a few characters first, bash requires you to type ^D twice before doing so. (The first ^D is treated like 'delete')
That's how the "EOF" character works (in "canonical" mode input, which is the default). It's actually never sent to the application, so it would be more accurate to call it the EOF signal.
The EOF character (normally Ctrl-D) causes the current line to be returned to the application program immediately. That's very similar to the behaviour of the EOL character (Enter), but unlike EOL, the EOF character is not included in the line.
If the EOF character is typed at the beginning of a line, then zero bytes are returned to the application program (since the EOF character is not sent). But if a read system call returns 0 bytes, that is considered an end-of-file indication. So at the beginning of a line, an EOF will be treated as terminating input; anywhere else, it will merely terminate the line and so you need two of them to terminate input.
For more details, see the .Posix terminal interface specification.

Double.parseDouble() equivalent in C++? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
std::string to float or double
I am writing a calculator (learning C++), and just decided to make a calculator, since that was the first thing I did when learning Java.
The program does the following:
Asks the user for the first number
Asks what the user wants to do with the number (-,+,*,/)
Asks for the second number
Displays the result.
when grabbing a number from the user in Java I used Double.parseDouble(number) to check if what they entered is a number or not.
Is there a similar command in C++? Ive been doing research and it seems like you have to use tricks such as comparing it to ASCII equivalents etc.. basically a ton of code for a simple task... so before i take that route, I wanted to stop by here and see if perhaps there is some sort of call I can make to check if the input is a number. I need it to validate negatives, zero and positives, as well as numbers with decimals... everything else should be rejected and the user should be asked for input again.
When I did it in Java I used try/catch statement and if the input was invalid it would return the method (in other words, itself) so it would loop and ask the user for input again.
Thanks!
You can use strtod. It handles underflow and out of range values in a convenient way.
Additionally, as Joachim Pileborg notes, if you use C++11 compliant compiler, there is std::stod in the standard library.
Use the function double atof(const char*) ;
example usage:
const char* = "3.14159";
double pi = atof(myDouble);
How about using isdigit function.