This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 2 years ago.
I am a newcomer to programming. My English is bad so I used google translate to ask this question:
I'm practicing using input/output in C language. I wrote a C program that takes a file called sample.txt and writes a few lines of words in it. I feel that the program that I made is correct but I found an error when compiling the program.
#include <stdio.h>
int main(){
FILE *fptr;
int n,I;
char text[100];
fptr=fopen("sample.txt","w");
printf("Number of line? ");
scanf("%d",&n);
printf("\n");
for( i = 1; i <= n; i++){
printf("Line %d: ", I);
fgets(text, sizeof(text), stdin);
fputs(text, fptr);
}
fclose(fptr);
return 0;
}
This is the output :
enter image description here.
enter image description here
Why line 1 and 2 are not separate like the others? I've checked several times and I don't know what went wrong.
As already pointed out by people in comments, you need to handle the newline left by scanf so that it doesn't get consumed by fgets() afterwards. You can either add a getchar() after scanf to handle this:
printf("Number of line? ");
scanf("%d",&n);
getchar();
Or you can replace usage of scanf for taking input with fgets() followed by a sscanf:
char input[10];
...
fgets(input, 10, stdin);
sscanf(input, "%d", &n);
When I made this changes, I was able to see desired output:
c-posts : $ ./a.out
Number of line? 3
Line 1: Foo
Line 2: Bar
Line 3: Pong
c-posts : $ cat sample.txt
Foo
Bar
Pong
Related
This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Why does printf not flush after the call unless a newline is in the format string?
(10 answers)
Closed 2 days ago.
I am new to C and am writing a very simple C program which just provides a input and repeats it back to you. The code shows the first print f which is a $ and lets you input something but will not print the text back to you. Here is the code:
char input[50];
printf("$");
scanf("%s\n", input);
printf("\n %s", input);
I thought it might have been a compile issue but nothing changes. I use make token which is the name of the file.
Remove the "\n" in the scanf() format string. The trailing "\n" instructs scanf() to match any number of white space characters and it will only know when it's done when encountering a non-white space character. Meanwhile you expect it to return after reading the first "\n". Consider using fgets() instead.
#include <stdio.h>
int main() {
char input[50];
printf("$");
scanf("%s", input);
printf("\n %s", input);
}
and example session:
$abc
abc
This question already has answers here:
fgets doesn't work after scanf [duplicate]
(7 answers)
Closed 1 year ago.
CODE:
#include<stdio.h>
#include<stdlib.h>
int main(){
struct mobile{
char N[10];
int ram, pixel, price;
}B[5];
int min;
char trash;
for(int i = 0; i < 5; i++){
printf("Enter Mobile Name: ");
fgets(B[i].N, sizeof(B[i].N), stdin);
printf("Enter features (ram/camera pixels/price): ");
scanf("%d%d%d", &B[i].ram, &B[i].pixel, &B[i].price);
printf("\n");
}
}
The program is not accepting value for name of mobile second time. It prints Enter mobile name but don't take value then print Enter features and ask for value. I tried adding a second scanf above printf("\n"); but didn't work. Help please. Thanks.
Remove \n from buffer
scanf leaves a newline in the buffer, which is then read by fgets. The other problem is, that you aren't dividing the user input using a delimiter so I would put a space or a slash between the type specifiers %d:
scanf("%d/%d/%d\n", &B[i].ram, &B[i].pixel, &B[i].price);
The input should then be something like this:
Enter specs (ram/pixels/price): 8/12/500
The trailing character \n is now being read, but it isn't stored in any variable.
Remove \n from fgets() input
This doesn't cause your problem, but I would also remove the trailing \n from the fgets() input, because it's probably not supposed to be part of the phone's name.
#include <string.h>
fgets(B[i].N, sizeof(B[i].N), stdin);
B[i].N[strcspn(B[i].N, "\n")] = '\0';
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 2 years ago.
In my program I have the user input a phrase, and I use the fgets function to retrieve it so it can count the spaces between words. The problem is my program skips over fgets and continues into the next scanf. Can someone explain what's the problem and how I can fix it?
#include<stdio.h>
#include<string.h>
int main(){
char plaintext[50], key[15];
char encrypt[50];
int EncryptOp = 1, DecryptOp = 2, choice;
printf("Enter 1 for Encryption or 2 For Decryption: ");
scanf("%d", &choice);
if(choice ==EncryptOp){
printf("Enter Plaintext for Encryption: ");
fgets(plaintext,50,stdin);
printf("Enter Keyword:");
scanf("%s", &key);
printf("Plaintext:%s\n Keyword:%s\n", plaintext, key);
}else if(choice ==DecryptOp){
printf("Enter Encrypted Message for Decryption: ");
scanf("%s", &encrypt);
}
return 0;
}
When I run it and choose 1 it outputs this:
Enter 1 for Encryption or 2 For Decryption: 1
Enter Plaintext for Encryption: Enter Keyword:
As you can see it doesn't allow the user to input the plaintext and goes right into asking them to enter a keyword.
Look here:
https://stackoverflow.com/a/20156727/14273548
Copied answer to here because of miminum characters.
after this line scanf("%d",&e) add a getchar() like this :
scanf("%d",&e);
getchar();
when you press Enter the newline character stays in the buffer so when fgets is called the newline is passed to it and it actes as if you pressed Enter
scanf() reads exactly what you asked it to, leaving the following \n from the end of that line in the buffer where fgets() will read it. I would recommend using fgets() for reading input too and using sscanf() to read choice integer:
char input[10];
...
fgets(input, 10, stdin);
sscanf(input, "%d", &choice);
This question already has answers here:
fgets doesn't work after scanf [duplicate]
(7 answers)
Closed 3 years ago.
I wrote a code to implement Julias Caesar Cryptography in C.
The problem is that my fgets() is not waiting for input and skipping to fputs().
#include<stdio.h>
int main(){
int size;
printf("Enter the size of the string: ");
scanf("%d",&size);
int key;
printf("Enter the key: ");
scanf("%d",&key);
char a[size];
printf("Enter the string: ");
fgets(a,size,stdin);
for(int i=0;i<size;i++){
a[i]+=key;
}
fputs(a,stdout);
return 0;
}
I used CodeBlocks 17.12 to compile this C program.
My OS is Windows 7 (32-bit)
Welcome to stackoverflow.
When you enter your answer, there is a newline char at the end (\n) in the buffer. When fgets() reads your input it reads the newline to. You can remove the newline, or use a regex to skip it, or fgets() once on the line so that you can use scanf() once more as suggested in this other answer that may help you.
And, please, remember to search in stackoverflow before posting a question!
This question already has answers here:
C skipping one command of a function? [duplicate]
(2 answers)
Closed 7 years ago.
I've written a C program to count the number of occurrences of an entered character. When I execute,I could only enter the file name.Before I enter the character to be counted , the next statement executes.The output I get is shown below.
Enter the file name
test.txt
Enter the character to be counted
File test.txt has 0 instances of
Here is my code
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp1;
int cnt=0;
char a,ch,name[20];
printf("Enter the file name\n");
scanf("%s",name);
//fp1=fopen(name,"r");
printf("Enter the character to be counted\n");
scanf("%c",&ch);
fp1=fopen(name,"r");
while(1)
{
a=fgetc(fp1);
if (a==ch)
cnt=cnt+1;
if(a==EOF)
break;
}
fclose(fp1);
printf("File %s has %d instances of %c",name,cnt,ch);
return 0;
}
How to resolve this?
It's a common beginners problem, especially when using the scanf family of functions.
The problem is that when you enter the file-name, and press Enter, the scanf function reads the text but leaves the Enter key, the newline, in the input buffer, so when you next read a character it will read that newline.
The solution is very simple: Tell scanf to read and discard any leading white-space by putting a single space in the scanf format:
scanf(" %c",&ch);
// ^
// |
// Note leading space
If you follow the link to the scanf reference it will tell you that almost all formats automatically reads and discards leading white-space, one of the three exceptions is just the format to read single characters, "%c".