I need to make the program in such a way that when the return key is entered it continues with the program and prints the initial lines again.
I tried to resolve it with (case '\n') but that didn't work and I tried some getchar() variants but I had the same issue.
void main()
{
char nameA[100];
char nameB[100];
char command;
int height;
int quit = 1;
struct node *ring1 = NULL;
struct node *ring2 = NULL;
while(quit)
{
printf("command? ");
scanf("%c", %command, 1);
switch (command)
{
case 'q':
printf("bye\n");
quit = 0;
break;
case 't':
printf("name? ");
scanf(" %[^\n]", nameA);
printf("height? ");
scanf(" %d", &height);
ring1 = insert_tail(ring1, nameA, height);
break;
case '\n':
break;
default:
break;
}
}
}
What I want to be able to print is
command?
command? ...
The problem is that if I use " %c" I will ignore the new line and if I use "%c" the output will look like:
command?
command? ...
but in the case that let's say I use the 't' command in my code the result will look like
command? t
name? Everest
height? 8848
command? command?
How can I fix that ? I assume the problems is because I actually enter two characters, the "t" and "\n" but I have no clue how to get around that.
How to ignore the '\n' character in the input
After all commands, except the bare '\n', consume the rest of the line.
In the t case, it is the '\n' after the entered height that the causes the issue. Consume it before looking for a new command.
while(quit) {
printf("command? ");
scanf("%c", &command);
switch (command) {
...
}
if (command != '\n') {
int ch;
while ((ch = getchar()) != `'\n'`) && (ch != EOF)) {
;
}
}
}
Tip: Consider using fgets() for user input and avoid using scanf().
Related
I want to break this loop when the user press enters twice. Meaning, if the user does not enter a character the second time, but only presses enter again, the loop must break.
char ch;
while(1) {
scanf("%c",&ch);
if(ch=='') { // I don't know what needs to be in this condition
break;
}
}
It is not possible to detect keypresses directly in C, as the standard I/O functions are meant for use in a terminal, instead of responding to the keyboard directly. Instead, you may use a library such as ncurses.
However, sticking to plain C, we can detect newline characters. If we keep track of the last two read characters, we can achieve similar behavior which may be good enough for your use-case:
#include <stdio.h>
int main(void)
{
int currentChar;
int previousChar = '\0';
while ((currentChar = getchar()) != EOF)
{
if (previousChar == '\n' && currentChar == '\n')
{
printf("Two newlines. Exit.\n");
break;
}
if (currentChar != '\n')
printf("Current char: %c\n", currentChar);
previousChar = currentChar;
}
}
Edit: It appears that the goal is not so much to detect two enters, but to have the user:
enter a value followed by a return, or
enter return without entering a value, after which the program should exit.
A more general solution, which can also e.g. read integers, can be constructed as follows:
#include <stdio.h>
#define BUFFER_SIZE 64U
int main(void)
{
char lineBuffer[BUFFER_SIZE];
while (fgets(lineBuffer, BUFFER_SIZE, stdin) != NULL)
{
if (lineBuffer[0] == '\n')
{
printf("Exit.\n");
break;
}
int n;
if (sscanf(lineBuffer, "%d", &n) == 1)
printf("Read integer: %d\n", n);
else
printf("Did not read an integer\n");
}
}
Note that there is now a maximum line length. This is OK for reading a single integer, but may not work for parsing longer input.
Credits: chux - Reinstate Monica for suggesting the use of int types and checking for EOF in the first code snippet.
You can store the previous character and compare it with the current character and enter, like this:
char ch = 'a', prevch = '\n';
while(1){
scanf("%c",&ch);
if((ch=='\n') && (ch == prevch)){// don't know what needs to be in this condition
break;
}
prevch = c;
}
Note that the previous character by default is enter, because we want the program to stop if the user hits enter at the very start as well.
Working like charm now
char ch[10];
while(1){
fgets(ch, sizeof ch, stdin);
if(ch[0]=='\n'){
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've made a user-defined function for reading input and replacing newline character '\n' with '\0' so when I use printf statement for printing the string it won't add newline at the end.
char xgets(char *line, int size, FILE *stdn)
{
//READS THE LINE
fgets(line, size, stdn);
//REMOVES NEWLINE CHARACTER '\n' AND ADDS '\0'
line[strcspn(line, "\n")] = '\0';
return line;
}
When I call xgets inside main() function it works properly, but when it is called in other user-defined function it does not wait for user-input.
I'm using Visual Studio 2015 for debugging my code.
Here's my code:
#include<stdio.h>
#include<stdlib.h>
#include<process.h>
//USER-DEFINED FUNCTION
char xgets(char *line, int size, FILE *stdn);
void sortm_hgrade();
void sortm_rcharge();
void header(void);
void header(void)
{
printf("*-*-*-*-*HOTEL_INFO*-*-*-*-*");
printf("\n\n");
}
char xgets(char *line, int size, FILE *stdn)
{
//READS THE LINE
fgets(line, size, stdn);
//REMOVES NEWLINE CHARACTER '\n' AND ADDS '\0' END LINE CHARACTER
line[strcspn(line, "\n")] = '\0';
return line;
}
#define MAX 1000
//PROGRAMS STARTS HERE
int main(void)
{
//VARIABLE-DECLARATION
int i = 0, j = 0, n = 0;
char line[MAX] = { 0 };
char o = { 0 };
char h[10] = { 0 };
//FUCNTION CALL-OUT
header();
printf("Type anything : ");
xgets(h, sizeof(h), stdin);
printf("Enter one option from the following : \n\n");
printf("(a) To Print out Hotels of a given Grade in order of charges. \n");
printf("(b) To Print out Hotels with Room Charges less than a given Value. \n");
printf("Please type a proper option. \n");
while (n == 0){
scanf_s(" %c", &o);
switch (o){
case 'a':
sortm_hgrade();
n = 1;
break;
case 'b':
sortm_rcharge();
n = 1;
break;
default:
printf("Option INVALID \n");
printf("Please type a proper option \n");
n = 0;
break;
}
}
//TERMINAL-PAUSE
system("pause");
}
void sortm_hgrade()
{
//FOR SORTING BY GRADE
char g[10] = { 0 };
printf("Enter the Grade : ");
xgets(g, sizeof(g), stdin);
printf("\n");
}
void sortm_rcharge()
{
printf("----");
}
You should change
scanf(" %c", &o);
to
scanf("%c ", &o);
This force scanf to consume trailing chars, like '\n'
In your code '\n' of user input for scanf %c is not consumed and it is consumed by fgets in your xgets function that exit immediately with an empty buffer.
BTW that solution can wok only if a single char is input by user.
Best code would be
char c;
while (n == 0)
{
o = getchar();
while ((c = getchar()) != EOF && c != '\n') ;
EDIT
With the second solution code is waiting, and discarding, chars until a '\n' is triggered or end of file. In your specific case (using stdin as console) EOF is not mandatory. It will be mandatory in case of input is being read from a "real file".
You need to skip the \n character after you take in a character. you can command scanf for that. fgets reads that newline character up first and then hence it terminates. use this
scanf(" %c *[^\n]", &o);
This should do the trick
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.
I have tried following code there is require %d before entering character. That is an after switch loop in code.
#include<stdio.h>
#include<conio.h>
void sum();
void mul();
void main()
{
char ch;
int c;
clrscr();
do
{
printf("\n\n Enetr choice ");
printf("\n\n\t 1: SUM \n\n\t 2: MUL");
scanf("\n\n\t %d",&c);
switch(c)
{
case 1:
sum();
break;
case 2:
mul();
break;
default:
printf("\n\n hhhh..... ");
}
printf("\n\n Want u calcualte again");
//scanf("%d");
scanf("%c",&ch);
printf("\n ch value is %c",ch);
}while(ch=='y'|| ch=='Y');
getch();
}
void sum()
{
int s;
s=10+50;
printf(" SUM: %d",s);
}
void mul()
{
int s;
s=10*50;
printf(" SUM: %d",s);
}
Here in this code after switch I tried to input character but without the scanf statement which is in comment is require while you input character. without that scanf statement compiler does not take character input. so please give me solution.
Its because you have to "eat up" the newline from previous input
You don't have to use %d.
Instead use:
while((c = getchar()) != '\n' && c != EOF) ;
in place of
//scanf("%d");
to discard the newline.
this is the problem occurred due to the insertion of next line character i.e. '\n' instead of following statement
scanf("%c",&ch);
you should use
scanf("\n%c",&ch);
Now what will happen firstly control goes to new line and then it will insert or input the character, just change this statement you will find your program execute properly...
You have to consume new line character.
You can add space before %c in your scanf statement to ignore white space
You should change
scanf("%c",&ch);
to
scanf(" %c",&ch);//this makes scanf ignore white spaces like new line, space etc.
or use getchar() to do it.
c=getchar();
For more insight go to question:
scanf() function doesn't work?
Another method that tells scanf to consume or recognize white space (and a new line is considered white space) is to code:
char ch[2];
...
scanf("%1s", &ch);
...
if (ch[0] == 'x' etc.