I took the following example literally from Walter Savitch Absolute C++ book. It works (as one would expect from a scholar such as Walter Savitch). However, I am puzzled why as I will explain after the code citation:
cout << "Enter a line of input and I will echo it:\n";
char symbol;
do
{
cin.get(symbol);
cout << symbol;
} while (symbol != '\n');
cout << "That's all for this demonstration.\n";
Possible output will look as follows:
Enter a line of input and I will echo it:
Do Be Do 1 2 34
Do Be Do 1 2 34
That's all for this demonstration.
My problem is the following. In going through the loop just once, cin.get(symbol) will find one character at a time, and cout will then output this one character consequently. Then, if my input wasn't a '\n' character, it will go into the loop for the second time, and so on, until finally the input equals '\n'.
However, in executing the code, all the input seems to be read at once, and then copied back at once. How can this happen if every input character needs to be checked to be equal to '\n'?
Final point, probably stating the obvious: this question does not pertain to code that is some way not syntactical. I am just puzzled about what happens during compilation and/or execution of the simple code I present above.
Hopefully someone can help me out!
Thanks.
Your observation is correct. It seems like all the input is read at once and then, printed out at once. The reason is that when the output is printed, it goes into a buffer which actually gets printed only when the buffer reaches a certain size, or whenever the code is all done. In the latter case, the output stream is closed and gets flushed. Practically speaking, this code is being printed but into a buffer.
Well it looks like it's gettings handled at once, because it is. The loop is going on exactly as you've written - keeps on writing the char until it meets the end of line mark. There isn't really much logic behind it :)
Related
i just have a quick question on this bit of code i have here on the Cryptopals Challenges, using Python3, For XORing a string with one single character.The program takes in a hex string string, decodes it, XORs it with a single character, does this for every possible character, then finds the "most english" line of XORd data. heres my code snippet (which i admittdly used from a solutions page ) :
def singlechar_xor(input_bytes, key_value):
"""XORs every byte of the input with the given key_value and returns the result."""
output = b''
for char in input_bytes:
output += bytes([char ^ key_value])
return output
i know what is happening and i understand what is supposed to happen, im just not sure how bytes behave and what types are and arent supposed to be XORd. Why do i need the brackets around char^key_value? If i remove the brackets my output becomes a bunch of 0's. What is the result of the XOR or the character and the key_value? If someone could kindly explain so i could have a better understanding going forward in these challenges id GREATLY appreciate it <3
Is there a way to prevent the program from executing characters in "Menu" type program where you choose options while running console and enter numbers only to do steps and browse data.
My program is a book catalog where you can review, change, add or delete information.
Things wouldn't be as bad but the the thing is, that when you enter a letter or non-number character the program gets messy and stuck.
I am not adding my code since I think that there should be a universal command to get rid of my problem + it would take some time to translate my code into EN.
The easiest way to do it is use the getline function I think. Instead of using cin >> num; for example, you would use getline(cin,value); where "value" is a string that you first store your input in. Then you can do num = atoi(value.c_str()); to save the string input as an integer value into "num". If "num" is a float, then just use atof instead of atoi. This way if the string is not a number, it just sets the value to 0. You could then use an if statement to display an error message if the value of num == 0. Hope that helps. Good luck!
If your application runs in a console and you are worried about wrong (non-number) input, perhaps you should the input not as a number, but as a text and then parse it to see it is really a number. If not, tell the user the input is incorrect and let them enter it again.
Which argument of write() sys-call is evaluated in an if block when the number of bytes are written either into standard input or standard output. In the following example (from the Beginning Linux Programming);
if(write(1, "Here is some data\n", 18) != 18)
write(2, "Write error in file descriptor 1\n", 46);
I tried to make the if statement false by making the string longer/shorter than 18 bytes but still it prints the string "Here is some data". The second write statement is evaluated only when I change the third argument from 18 to 17 or 19. It seems the if condition is evaluated only by the third argument as it shouldn't be the case. Please help me understand it.
I think you're trying to ask a different question, but I'm not sure what it is. The answer currently is: all of them.
All arguments to write have to be evaluated, so the function can be called, so the comparison can be made.
What I'm guessing you may be asking is: why doesn't changing the string length change the number of bytes written. That's because C will happily let you read past the end of your string. If you specify that 18 bytes are to be sent, 18 will be sent, whether that means sending only part of the string, or reading some garbage behind the "\n" to make it 18.
The first call:
write(1, "Here is some data\n", 18)
is always executed. When number of written characters are not 18 (corresponds to "!= 18" from the code), also the second call is executed:
write(2, "Write error in file descriptor 1\n", 46);
[Ubuntu 14.04, GNU Awk 4.0.1]
I have a strange problem... I am assigning a numeric value, that is retrieved from an input file, to a custom variable. When I print it, it displays correctly, and printing its length displays the right number of digits.
However, when I use the variable in a loop, my loop stops when index becomes greater than the most significant digit of my variable.
I have tried a For Loop, and now a While Loop, both suffer the same problem.
With the file I'm processing, samples contains the value 8092, and the loop stops on the 9th iteration.
#!/usr/bin/awk -f
BEGIN {
samples = 0;
}
{
...
samples = $24;
}
END {
i = 1;
while (i <= samples ) {
if (i>samples) { print "This is the end.\n " i " is bigger than " samples;}
i++;
}
}
I am very new to AWK, and can't see why this is occurring. After reading a number of tutorials, I'm under the impression that AWK is able to convert between string & numeric representations of numbers as required.
Can someone help me see what I've done wrong?
Solution
The answer was, as JNevill & ghoti suggested, to add 0 to the variable. In my case, the best place was just before the loop, as samples` is rewritten during the body of the AWK script. Thanks.
Awk doesn't exactly "convert" between representations, it simply uses whatever you give it, adjusting context based on usage. Thus, when evaluating booleans, any non-zero number evaluates to TRUE, and any string except "0" evaluates to TRUE.
I can't see what's really in your samples variable, but if you want to force things to be evaluated as a number before you start your loop, you might be able to simple add zero to the variable I.e.:
samples = $24 + 0;
Also, if your source data came from a DOS/Windows machine and has line endings that include carriage returns (\r\n), and $24 is the last field on each line, then you may be comparing i against 24\r, which is likely not to give you the results you expect.
To see what's really in your input data, try:
cat -vet samples | less
If you see ^M before the $ at the end of each line, then your input file contains carriage returns, and you should process it appropriately before asking awk to parse its content.
In fact, I think it's pretty clear that since your input data begins with the character "8" and your loop stops on the 9th iteration, your comparison of i to samples is one of strings rather than numbers.
awk decides the type of variable depending on what value is held in the variable. You can force it to type the way you want, though it's a bit hackey (isn't everything though).
Try adding 0 to your variable before hitting the for loop. $sample = $sample + 0, for instance. Now no matter what awk thought before you hit that line, it will now treat your number as a number and your for loop should execute as expected.
Odd though that it was executing at all and stopping at 9 iterations.... It suggests that perhaps it is already treating it correctly and you may be assuming that the value is 8092, when it is, in fact 9. Also, that printed bit inside your for loop should never execute. Hopefully it doesn't output that.
I have seen a lot of C/C++ based solutions to this problem where we have to write a program that upon execution prints its own source.
some solutions --
http://www.cprogramming.com/challenges/solutions/self_print.html
Quine Page solution in many languages
There are many more solutions on the net, each different from the other. I wonder how do we approach to such a problem, what goes inside the mind of the one who solves it. Lend me some insights into this problem... While solutions in interpreted languages like perl, php, ruby, etc might be easy... i would like to know how does one go about designing it in compiled languages...
Aside from cheating¹ there is no difference between compiled and interpreted languages.
The generic approach to quines is quite easy. First, whatever the program looks like, at some point it has to print something:
print ...
However, what should it print? Itself. So it needs to print the "print" command:
print "print ..."
What should it print next? Well, in the mean time the program grew, so it needs to print the string starting with "print", too:
print "print \"print ...\""
Now the program grew again, so there's again more to print:
print "print \"print \\\"...\\\"\""
And so on.
With every added code there's more code to print.
This approach is getting nowhere,
but it reveals an interesting pattern:
The string "print \"" is repeated over and over again.
It would be nice to put the repeating part
into a variable:
a = "print \""
print a
However, the program just changed,
so we need to adjust a:
a = "a = ...\nprint a"
print a
When we now try to fill in the "...",
we run into the same problems as before.
Ultimately, we want to write something like this:
a = "a = " + (quoted contents of a) + "\nprint a"
print a
But that is not possible,
because even if we had such a function quoted() for quoting,
there's still the problem that we define a in terms of itself:
a = "a = " + quoted(a) + "\nprint a"
print a
So the only thing we can do is putting a place holder into a:
a = "a = #\nprint a"
print a
And that's the whole trick!
Anything else is now clear.
Simply replace the place holder
with the quoted contents of a:
a = "a = #\nprint a"
print a.replace("#", quoted(a))
Since we have changed the code,
we need to adjust the string:
a = "a = #\nprint a.replace(\"#\", quoted(a))"
print a.replace("#", quoted(a))
And that's it!
All quines in all languages work that way
(except the cheating ones).
Well, you should ensure that you replace only
the first occurence of the place holder.
And if you use a second place holder,
you can avoid needing to quote the string.
But those are minor issues
and easy to solve.
If fact, the realization of quoted() and replace()
are the only details in which the various quines really differ.
¹ by making the program read its source file
There are a couple of different strategies to writing quines. The obvious one is to just write code that opens the code and prints it out. But the more interesting ones involve language features that allow for self-embedding, like the %s-style printf feature in many languages. You have to figure out how to embed something so that it ends up resolving to the request to be embedded. I suspect, like palindromes, a lot of trial and error is involved.
The usual approach (when you can't cheat*) is to write something that encodes its source in a string constant, then prints out that constant twice: Once as a string literal, and once as code. That gets around the "every time I write a line of code, I have to write another to print it out!" problem.
'Cheating' includes:
- Using an interpreted language and simply loading the source and printing it
- 0-byte long files, which are valid in some languages, such as C.
For fun, I came up with one in Scheme, which I was pretty proud of for about 5 minutes until I discovered has been discovered before. Anyways, there's a slight modification to the "rules" of the game to better count for the duality of data and code in Lisp: instead of printing out the source of the program, it's an S-expression that returns itself:
((lambda (x) (list x `',x)) '(lambda (x) (list x `',x)))
The one on Wikipedia has the same concept, but with a slightly different (more verbose) mechanism for quoting. I like mine better though.
One idea to think about encoding and how to give something a double meaning so that it can be used to output something in a couple of forms. There is also the cavaet that this type of problem comes with restrictions to make it harder as without any rules other than the program output itself, the empty program is a solution.
How about actually reading and printing your source code? Its not difficult at all!! Heres one in php:
<?php
{
header("Content-Type: text/plain");
$f=fopen("5.php","r");
while(!feof($f))
{
echo fgetc($f);
}
fclose($f);
}
?>
In python, you can write:
s='c=chr(39);print"s="+c+s+c+";"+s';c=chr(39);print"s="+c+s+c+";"+s
inspired from this self printing pseudo-code:
Print the following line twice, the second time with quotes.
"Print the following line twice, the second time with quotes."
I've done a AS3 example for those interested in this
var program = "var program = #; function main(){trace(program.replace('#',
String.fromCharCode(34) + program + String.fromCharCode(34)))} main()";
function main(){
trace(program.replace('#', String.fromCharCode(34) + program + String.fromCharCode(34)))
}
main()
In bash it is really easy
touch test; chmod oug+x test; ./test
Empty file, Empty output
In ruby:
puts File.read(_ _ FILE _ _)