I have tried this :
switch(c)
case 13 : {printf("enter pressed");break;}
and this :
switch(c)
case '\n' : {printf("enter pressed");break;}
but It didn't work out
Try to use '\r' instead.
The 'Enter' key represent Carriage Return that is the same as '\r'.
"Enter" represents a new line character in C language.
So you can use its ascii value i.e. 10 for its representation.
Eg :
#include<stdio.h>
Try this code :
int main()
{
char ch = '\n';
printf("ch = %d\n", ch);
}
Later you can use the following code as a test for switching '/n'
int main()
{
char ch = '\n';
switch(ch)
{
case '\n' :
printf("Enter pressed\n");
break;
default :
//code
}
}
This program reads from standard input and writes "enter pressed" whenever a newline occurs in the input:
#include <stdio.h>
int main()
{
int c;
for (;;) {
c = getc(stdin);
switch (c) {
case '\n':
printf("enter pressed\n");
break;
case EOF:
return 0;
}
}
}
I think this is what you are looking for.
You might be missing the trailing \n in your printf-call, causing the message to be buffered for output but maybe not flushed so it appears on the screen.
Related
I have a program that reads user input as such:
char c;
scanf("%c", &c);
and then checks if it is a digit:
if(isdigit(c)) {
int f = atoi(c);
return f;
}
switch(c) {
case 'q':
exit(1);
break;
...
}
...
Example program:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
char c;
scanf("%c", &c);
if(isdigit(c)) {
int f = atoi(&c);
printf("f: %d\n", f);
return f;
}
switch(c) {
case 'q':
printf("q\n");
return -1;
break;
}
return 0;
}
However when I enter, for exmaple, 10 then the input becomes 1 and 0 and \n. I want 10. How do I read "10" and "100" and "4" for example as well as other characters such as "q"?
char variables are only capable of saving one character. So if you want to have multiple characters (numbers are also characters) in a char variable you have to use string or char VARIABLE[size] . For example: char variable[10] can save up to 10 characters. But then you can't use isdigit() in that way anymore. Instead you have to use a loop to check each character of the string.
So I've tried so much but I can't input a string even using: fgets, gets, scanf, and scanf("%[^\n]%*c",pharse). I need a string with the spaces. It just jumps the code line of input I think.
Please answer with a explanation of why it doesn't work
https://repl.it/#YashKumar11/String#main.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
const int DIMMAX=100;
char pharse[DIMMAX+1];
int stringLength;
int choice=0;
while(choice != '5'){
printf("1)Enter a new pharse.");
printf("\n2)");
printf("\n3)");
printf("\n4)");
printf("\n5)\n");
scanf("%d",&choice);
switch(choice){
case 1:
printf("\n=====================\n");
scanf ("%[^\n]%*c",pharse); //<-----------------------It jumps here
printf("\n=====================\n");
stringLength = strlen(pharse);
printf("%s",pharse);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
printf("\nNot a valid option.\n\n");
break;
}
}
return 0;
}
the statement to input the parase fails because the input for choice leaves a \n in the input stream.
When the second call to scanf() is made, it immediately returns (with a returned value of 0) because the first character input is \n.
suggest following each call to scanf() with:
int ch;
while( (ch = getchar()) != '\n' && ch != EOF );
that also implies that the format string of the second call to scanf() should have the %*c removed.
Your problem is not in the line that you try to read the string, but in the previous call to scanf()
scanf() was written to scanf formatted input. Keyboard input is not that. It can be everything except formatted. The user has over 100 keys to choose from
When the user types a '1' to input a phrase scanf() does not consume the newline. In fact the user can type 1 here we go to enter some text!
and then ENTER. And scanf() will be ok with just the '1'. The rest of the chars would be left there for the program to read. scanf() has no way to know what is left there.
Also scanf() return an int with the number of values read, and it can be zero if the user entered no digits. And you did not tested in your code.
Compare with your code a bit modified below
#define DIMMAX 100
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
char phrase[DIMMAX + 1];
int stringLength;
printf("1) Enter a new phrase");
printf("\n2)");
printf("\n3)");
printf("\n4)");
printf("\n5) Exit\n\nOption: ");
fgets(phrase, DIMMAX, stdin);
while (phrase[0] != '5')
{
switch (phrase[0]) {
case '1':
printf("\n=====================\n");
fgets(phrase, DIMMAX, stdin);
printf("\n=====================\n");
stringLength = strlen(phrase);
phrase[strlen(phrase) - 1] = 0; // deletes the '\n'
printf("Phrase: '%s', len = %zd\n\n", phrase, strlen(phrase));
break;
case '2':
break;
case '3':
break;
case '4':
break;
case '5':
break;
default:
printf("\n'%c' (dec %d) is not a valid option.\n\n",
phrase[0], phrase[0]);
break;
}
printf("1) Enter a new phrase");
printf("\n2)");
printf("\n3)");
printf("\n4)");
printf("\n5) Exit\n\nOption: ");
fgets(phrase, DIMMAX, stdin);
}; // while()
return 0;
}
Maybe it helps to understand.
Note that instead of stopping rigth at the digit, like scanf(), fgets() read up to and including the newline, so if you are using printf() and not puts() to output it, you must take the last byte off the string read
In class I need to use scanf to get integers to work with. Problem is I do not know to end the while loop. I wait for '\n' in the code, but it is passing all tests. The program has to complete for grading.
How to make code work when input includes several '\n' in input and spacebars at the end of input.
All numbers are given with spacebar between.
# include <stdio.h>
int main()
{
int numbers;
char ch;
int stop = 0;
while(scanf("%d%c", &numbers, &ch))
{
if((ch == '\n') stop++;
#my_code
if (stop == 1) break;
}
while(scanf("%d%c", &numbers, &ch)) { if((ch == '\n') .... has a couple of problems.
If the line of input has only white-space like "\n" or " \n", scanf() does not return until non-white-space is entered as all leading white-spaces are consumed by "%d".
If space occurs after the int, the "\n" is not detected as in "123 \n".
Non-white-space after the int is discarded as in "123-456\n" or "123x456\n".
how to end loop?
Look for the '\n'. Do not let "%d" quietly consume it.
Usually using fgets() to read a line affords the more robust code, yet sticking with scanf() the goal is to examine leading white-space for the '\n'
#include <ctype.h>
#include <stdio.h>
// Get one `int`, as able from a partial line.
// Return status:
// 1: Success.
// 0: Unexpected non-numeric character encountered. It remains unread.
// EOF: end of file or input error occurred.
// '\n': End of line.
// Note: no guards against overflow.
int get_int(int *dest) {
int ch;
while (isspace((ch = fgetc(stdin)))) {
if (ch == '\n') return '\n';
}
if (ch == EOF) return EOF;
ungetc(ch, stdin);
int scan_count = scanf("%d", dest);
return scan_count;
}
Test code
int main(void) {
unsigned int_count = 0;
int scan_count;
int value;
while ((scan_count = get_int(&value)) == 1) {
printf("%u: %d\n", ++int_count, value);
}
switch (scan_count) {
case '\n': printf("Normal end of line.\n"); break;
case EOF: printf("Normal EOF.\n"); break;
case 0: printf("Offending character code %d encountered.\n", fgetc(stdin)); break;
}
}
I'm trying to write a short program that puts each word on a new line. The new line can be confirmed by tabulator, space or enter. The end of program is putting "#" in console. I have the problem that when I put "enter" to the console it writes next characters in the same line.
The second idea is to make all of this in a table, so I can put formatted text all together in the end. I can't figure this out either.
#include<stdio.h>
#include <conio.h>
#define STOP '#'
int main()
{
char ch;
while ((ch = (_getch())) != STOP) {
switch (ch) {
case '\n':
printf("\n");
break;
case '\t':
printf("\n");
break;
case ' ':
printf("\n");
break;
default:
putchar(ch);
}
}
printf("\nEND");
_getch();
return 0;
}
Because hitting "enter" issues a carriage return char (\r), not a linefeed one.
I noticed it when the cursor jumped back at the start of the line when I pressed "enter".
Fix your code like this (factorize the case statements too):
#include<stdio.h>
#include <conio.h>
#define STOP '#'
int main()
{
char ch;
while ((ch = (_getch())) != STOP) {
switch (ch) {
case ' ':
case '\t':
case '\r': // what was missing
printf("\n");
break;
default:
putchar(ch);
}
}
printf("\nEND");
_getch();
return 0;
}
You probably get a carriage return ('\r') which is what Return typically generates.
So you need to check for that, too. Your code can be simplified:
int main(void)
{
while((ch = _getch()) != STOP)
{
if(ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t')
ch = '\n';
putchar(ch);
}
}
Since we're always printing exactly one character per iteration, no need to use multiple printing functions. Also, using printf() to print a single constant character is overkill.
I am running a C program in Code :: Blocks in windows XP.
I am getting an error as
"drawing operation is attempeted when there was no current window"
What might cause this and how can I solve it?
My code is as follows:
#include <stdio.h>
#include <conio.h>
static int get_code(void);
// System dependent key codes
enum
{
KEY_ESC = 27,
ARROW_UP = 256 + 72,
ARROW_DOWN = 256 + 80,
ARROW_LEFT = 256 + 75,
ARROW_RIGHT = 256 + 77
};
int main(void)
{
int ch;
puts("Press arrow keys, escape key + enter to exit:");
while (( ch = get_code()) != KEY_ESC )
{
switch (ch)
{
case ARROW_UP:
printf("UP\n");
break;
case ARROW_DOWN:
printf("DOWN\n");
break;
case ARROW_LEFT:
printf("LEFT\n");
break;
case ARROW_RIGHT:
printf("RIGHT\n");
break;
}
}
getchar(); // wait
return 0;
}
static int get_code(void)
{
int ch = getch(); // Error happens here
if (ch == 0 || ch == 224)
ch = 256 + getch();
return ch;
}
the α came from the getche() input, it prompts the user for input and when the user press a key then enter it echos that key on the standard output "screen" and since the arrows are non-printable keys that's what happened you can do something like like this:
switch (ch)
{
case ARROW_UP:
printf("\bUP\n");
break;
case ARROW_DOWN:
printf("\bDOWN\n");
break;
case ARROW_LEFT:
printf("\bLEFT\n");
break;
case ARROW_RIGHT:
printf("\bRIGHT\n");
break;
}
actually conio.h is not standard header file which is not supported in Code :: Blocks
http://en.wikipedia.org/wiki/C_standard_library
getch() definition found only in conio.h so it shows error
try scanf to get user input.
Code::Blocks(MinGW) doesnt have conio.h header file. So you cant use the getch() function.