Use "while" to check if there is a blank line C - c

The code is to check if there is a blank line. I thought when I enter some text, it will keep doing the printf(), because it is stuck in the loop. But in fact, it just does the printf() once, and waits for another line of text. Why? Is it because the input will be wiped after the gets() function?
Here is the code
int main(){
char input[257];
char *ptr;
puts("Enter text a line at a time, then press Enter");
puts("Enter a blank line when done");
while( *(ptr= gets(input)) != NULL){
printf("You've entered: %s\n", input);
}
puts("Thank you and goodbye\n");
return 0;
}

this while should do the trick
while( (ptr= gets(input)) != NULL && input[0]!='\0')

Related

How to fix - unexpected output using getchar() and do-while

I am trying to make a simple code that will read a char from input and execute "Correct" or "Incorrect input" and run the code again until the correct input is entered. First of all it does not work for capital X. The other issue that I want to fix is that after the incorrect input I have to press enter to get the "Enter x" message, instead of getting in immediately after the incorrect input message.
#include <stdio.h>
int main()
{
do
{
printf("Enter x\n");
if (getchar()=='x'|| getchar()=='X')
{
printf("Entered char is X\n");
return 0;
}
else
{
printf("Input incorrect! Please try again!!!\n");
}
}
while (getchar()!='x' || getchar()!='X');
return 0;
}
You need to store the input in a variable, otherwise you keep asking for input several times in a row, for each getchar call.
For weird historic reasons, getchar actually returns an int, since the value EOF that can be returned from it is an int. So the variable must be int.
And finally, each time the user hits enter, a invisible line feed character \n is appended to the input stream. This character does you no good, so you should discard it with an extra read.
#include <stdio.h>
int main (void)
{
int input;
do
{
printf("Enter x\n");
input = getchar();
getchar(); // extra getchar to chew up line feed from stdin
if (input=='x'|| input=='X')
{
printf("Entered char is X\n");
}
else
{
printf("Input incorrect! Please try again!!!\n");
}
} while (input!='x' && input!='X');
return 0;
}
Please note that the opposite of input=='x'|| input=='X' is input!='x' && input!='X' (De Morgan's laws). "If input is not 'x' and input is not 'X' then loop".
When you hit the ENTER key the newline character \n is placed in input buffer. You need to consume that newline character in order to read the next character.
Also you are reading two time, which is unnecessary in this case. So your code should be like this
#include <stdio.h>
int main()
{
char inp;
do
{
printf("Enter x\n");
inp = getchar();
getchar(); // reading the newline character '\n'
if (inp == 'x'|| inp =='X')
{
printf("Entered char is X\n");
return 0;
}
else
{
printf("Input incorrect! Please try again!!!\n");
}
}
while (inp !='x' || inp !='X');
return 0;
}
p.s There is no need to put condition checking in while loop, since you are returning in if condition. while(true) would work fine. Thanks #bruno for pointing that out.
In your code:
if (getchar()=='x'|| getchar()=='X')
getchar() is called twice.
Instead, you should write it this way:
char c = getchar();
if (c=='x'|| c=='X')
for the second part, if your goal is print the message on a new line, then just simply change your printf to:
printf("\nInput incorrect! Please try again!!!\n");

want to insert multiple characters to a file in c(single at a time)

i have been trying to input characters and the character should be put in the file unless users change the value of opt to 'n'.
#include<stdio.h>
void main()
{
char ch,opt='y';
FILE *fp;
fp=fopen("myfile.txt","w");
while(opt=='y' || opt =='Y')
{ scanf("%c",&ch);
fputc(ch,fp);
printf("want to enter more characters(y or n):");
scanf("%c",&opt);
}
fclose(fp);
}
So I want to give the inputs until opt value changes to 'n'.
If you are using Windows OS then you can use following code to read characters without pressing Enter. See here and here to know about reading characters without pressing Enter on Linux plateforms.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch,opt='y';
FILE *fp;
fp=fopen("myfile.txt","w");
while(opt=='y' || opt =='Y')
{
ch = getch();
fputc(ch,fp);
printf("%c\nWant to enter more characters(y or n):", ch);
opt = getch();
printf("%c\n", opt);
}
fclose(fp);
}
Note: You can modify the code if you don't need to print the last entered character. See here to know other variants of getch() function.
Let's say you type a and press Enter.
When you do that, there are two characters in the input stream: 'a' and '\n'. The first scanf reads the 'a' into ch and the second scanf reads the '\n' into opt. That is the source of your problem.
You'll have to write code to read and discard the newline character. Here's one way to do it.
while(opt=='y' || opt =='Y')
{
scanf("%c",&ch);
fputc(ch,fp);
// Assuming that no more than one characte is entered per line,
// read the discard the newline.
fgetc(stdin);
printf("want to enter more characters(y or n):");
scanf("%c", &opt);
// Read and discard the newline again.
fgetc(stdin);
}
If you want to be a bit more flexible about your input, you can use:
// Make it as large as you need it to be.
#define LINE_LENGTH 200
int main()
{
char line[LINE_LENGTH];
FILE *fp;
fp=fopen("myfile.txt","w");
// Read a line of text.
while( fgets(line, LINE_LENGTH, stdin) != NULL )
{
// Print the line to the output file
fputs(line, fp);
printf("want to enter more characters(y or n):");
// Read the entire line again.
if( fgets(line, LINE_LENGTH, stdin) != NULL )
{
// If the entire line is just "n" or "N", break from the loop.
if ( strcmp(line, "n\n") == 0 || strcmp(line, "N\n") == 0 )
{
break;
}
}
}
fclose(fp);
}

Calling function in if statement or switch not working properly

When I compile and run this the output is:
press n to continue
n
Enter the filename: [ �h�� ]
But, if I call the new(); directly it run perfectly. But when I call new(); in if statement or switch statement, it shows the above output.
I tried scanf, fgets and gets in the new() fucntion but still not working.
#include<stdio.h>
#include<stdlib.h>
int menu();
int new();
int main(){
menu();
return 0;
}
int menu(){
printf("press n to continue\n");
//char c = getc(stdin);
char c = getchar();
if(c=='n'){
new();
}
else if(c==27){
return 0;
}
}
int new(){
char filename[50];
printf("Enter the filename: ");
//fgets(filename, 50, stdin);
scanf("%[^\n]s", filename);
printf("[ %s ]\n\n", filename);
return 0;
}
getchar() will read one character from stdin and leave the \n. So when you call scanf - it stops immediately and you got nothing. To skip whitespaces and start reading from non-space character add space before format.
scanf(" %49[^\n]", filename);
Do not mix %[] and %s
Always specify max number of chars to read (leaving one additional char for nul-terminator)
And compile with highest warning level - so you do not leave menu function without return.
Oh. and check the return value of scanf
if(scanf(" %49[^\n]", filename) == 1)
printf("[ %s ]", filename);

Console not waiting for input. (C language)

When I execute my code below. It waits for my input for entering a file name. But it doesn't wait for me to enter a filename, but rather just skips it to the _getch() part of it. I'm unable to add a sentence.
Code not working:
#include <stdio.h>
main() {
FILE *fp;
char fnamer[100] = ""; //Storing File Path/Name of Image to Display
printf("\n\nPlease Enter the Full Path of the Image file you want to view: \n");
scanf("%s", &fnamer);
fp = fopen(fnamer, "w");
if (fp == NULL)
{
printf("\n%s\" File NOT FOUND!", fnamer);
}
char c[1000];
printf("Enter a sentence:\n");
gets(c);
fprintf(fp, "%s", c);
fclose(fp);
_getch();
}
Code that works and waits for entering a sentence:
#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
char c[1000];
FILE *fptr;
fptr = fopen("program.txt", "w");
if (fptr == NULL){
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
gets(c);
fprintf(fptr, "%s", c);
fclose(fptr);
return 0;
}
Both are so similar right there in the end for the prompt asking for a sentence. It doesn't make sense.
you have to flush your input after using scanf.
put a getchar() after every scanf
You are encountering a very common problem when using stdin to receive input, which is after your first scanf call there is a dangling \n character which gets stuck in the buffer from the enter key. To clear this buffer in a portable easy way, add something like
char c;
while ( (c = getchar()) != '\n' && c != EOF ) { }
This simply initializes a character, and then calls get char as many times as needed until it reaches '\n' or 'EOF', which is immediately in your case.
tl;dr :
Your buffer looks like this
hello.txt\n <-- "comes from the enter key"
and when you try to use get(c) it takes the \n as the next enter key.
The rule is never mix scanf and [f]gets. scanf stops before the next unused character, generaly a blank, and the end of line is composed of blank characters.
You could try to put a dummy fgets between the last scanf and the first real fgets. That will ensure that you are now positionned on a beginning of line before reading. Alternatively, you could read everything in lines with fgets, and parse the lines with sscanf. That is what I prefere as soon as I want my input to be line oriented. And always control return values of input functions, it will avoid a progam suddenly going mad without any indication simply because one input gave an ignored error.
And last and not least: never use gets but only fgets, the former is for decades in the hall of shame as the cause of uncountable buffer overflows
Code could become:
#include <stdio.h>
#include <string.h>
main() {
FILE *fp;
char fnamer[100] = ""; //Storing File Path/Name of Image to Display
char c[1000], *ix;
int cr;
printf("\n\nPlease Enter the Full Path of the Image file you want to view: \n");
cr = scanf("%s", &fnamer);
if (cr != 1) {
// process error or abort with message
}
fp = fopen(fnamer, "w");
if (fp == NULL)
{
printf("\n%s\" File NOT FOUND!", fnamer);
return 1; // do not proceed after a fatal error!
}
for(;;) { // read until a newline in input
ix = fgets(c, sizeof(c), stdin);
if (ix == NULL) {
// end of input: abort
}
if (strcspn(c, "\n") < strlen(c)) break;
}
printf("Enter a sentence:\n");
ix = fgets(c, sizeof(c), stdin);
c[strcspn(c, "\n")] = '\0'; // remove end of line to get same data as gets
fprintf(fp, "%s", c);
fclose(fp);
_getch();
}
main() {
FILE *fp;
char fnamer[100]=""; //Storing File Path/Name of Image to Display
printf("\n\nPlease Enter the Full Path of the Image file you want to view: \n");
fgets ( fnamer,100,stdin); //fgets(name, sizeof(name), stdin);
fp=fopen(fnamer,"w");
if(fp==NULL)
{
printf("\n%s\" File NOT FOUND!",fnamer);
getch();
exit(1);
}
}
I Think best way to do,use fgets insted of scanf,Because
fgets() can read any open file, but scanf() only reads standard input(user given).
fgets() reads a line of text from a file; scanf() can be used for that but also handles conversions
from string to built in numeric types

Cant read input line in C

Sorry for a stupid question, but this is really starting to annoy me.
I need to take a line of input from a console. Here's the relavent fragment of code:
int number_read=0;
char line[80];
printf("Enter register address: ");
number_read = scanf("%s\n", line);
printf("number of characters entered: %d; characters entered: %s.\n", number_read, line);
if (number_read > 0) {
<read some registers and display the results.>
}
It doesn't work. The "Enter register address" line is printed, and the cursor stops at the end of the line, and moves to the next line when I press enter, but then nothing else happens. I've tried replacing scanf() with fscanf(stdin,...), with fgets(stdin), gets, GNU's getline(), a short function that does the same thing, with diagnostics:
char *new_line, ch;
for(;;) {
ch = fgetc(stdin);
if(ch == EOF) break;
if((*line++ = ch) == '\n') break;
printf("Line so far: %s\n", line);
}
*line='\0';
I get the same response from all of them. I'm including all the requisite headers.
I'm on a Windows XP box, compiling with gcc 3.4.5 (mingw).
Can anyone see what I'm doing wrong?
In scanf you should use a %i to represent a int so, try with
scanf("%I", number_line);
The following code will works,
char buff_msg[1024];
while(1)
{
if(fgets(buff_msg,1024, stdin) != NULL){
printf("%s\n", buff_msg);
memset(buff_msg, 0, 1024); // you will need this line
}
}
You can
break the loop on your own condition
try read() it works in MinGW replace
this
number_read = scanf("%s\n", line);
with this also include #include<unistd.h>
number_read = read(STDIN_FILENO, (void *)line,sizeof line);
value scanf returns is not the number of strings in the number of elements to read(this case meybe 1).
Use the %n To get the number, such as desired.
scanf("%s%n", line, &number_read);
printf("number of characters entered: %d; characters entered: %s.\n", number_read, line);

Resources