The reading of the standard input can be a bit boring sometimes - the scanf and printf functions were written more than 30 years ago, when the capacity of the terminals (and interface to the programs in general) were well heated than they are today.
The default entry works as a text file - which for the sake of typing, unless you change some very complicated settings, is always read line by line - so even using %c
in the scanf
, or the function getchar
as suggested in the other reply, the user will have to press <enter>
- and that <enter>
will be read - or next scanf
, or the next getchar
.
The best is not to try to read character by character - the user will have to press enter even. If you want to create an interface that responds to keyboard shortcuts, then it is best to use a console library, such as ncurses - it makes adjustments to the stdin configuration so that you can read key to key without side effects. But this is a stage beyond familiarization with the language that is the point of your current program - and possibly, it’s worth learning to use a graphical library for interface rather than ncurses (gtk, Qt, etc...)
Finally, for your current program, use the scanf with "%s" - but - remember, at all times that using scanf to read a string, it is necessary to think about what would happen if the user typed more data than fits into his string to store the data. Simple: too much data leaks into other memory regions in use by your program and this causes the famous "buffer overflow". To mitigate this, the "%s" must be used with the maximum number of characters that the user must type, between "%" and the "s" - scanf("%21s")
- accepts a string of up to 20 characters (plus the final x00).
Your program can be done like this:
char op[3]; //suficiente para conter a letra da opção, o \n e o \x00
...
scanf("%2s", op) // op já é um ponteiro - não precisa do &
...
while (op[0] != 's') && (op[0] != 'n') // verifica apenas o 1º caractere da string op
What do you mean 'not stop' ? you can show how it comes out on the console?
– Rodrigo Santiago
i answered below - but there’s a tip off topic: if you want to learn programming logic, without having to worry about low-level file stream logic, memory allocation, and still have programs that can do real tasks, try a higher level language like Python or Ruby. In C/C++, a simple reading of user input can, in addition to the problems you’ve had, add dangerous security holes - see my answer.
– jsbueno