Problems with scanf and or fgets program cuttoff - c

I am trying to write a code that reads in a integer using scanf and then asks the user if they would like to enter another by entering "yes" or "no". I get no errors when I compile but when I run the program it asks for the number, displays it as it should, ask to continue and then promptly closes without taking any input.
int main()
{
int *data=malloc(1*sizeof(int));
if(data==NULL)
{
printf("out of memory");
exit(1);
}
char *yc="yes";
char uinput[20];
int numinput;
printf("enter a number \n");
scanf("%d",&numinput);
data[0]=numinput;
printf("you entered %d \n",numinput);
printf("would you like to enter another # ?");
fgets(uinput,sizeof(uinput),stdin);
int count=0;
int n,i;
int comp=strncmp(uinput,yc,1);
while(comp==0)
{
n=sizeof(data)/sizeof(data[0]);
count=count+1;
data=(int*)realloc(data,n+1);
printf("enter another number:\n");
scanf("%d",&numinput);
data[n+1]=numinput;
printf("the numbers are:\n");
for(i=0;i<=count;i++)
{
printf("%d\n",data[i]);
}
printf("would you like to enter another # ?");
fgets(uinput,sizeof(uinput),stdin);
}
printf("Goodbye!\n");
return(0);
}
This is what happens when I run the program
./vector_play.out
enter a number
6
you entered 6
would you like to enter another # ?Goodbye!
I am not sure why it is immediately exiting any help would be great.

Your problem stems from the fact that after numinput has been read using the code in
scanf("%d",&numinput);
the newline character is still left in the input stream. The call to fgets reads the newline as a complete line and returns without waiting for any further input.
You need to add a line to ignore the rest of the input stream. You can use fgets for that purpose too.
scanf("%d",&numinput);
fgets(uinput,sizeof(uinput),stdin); // Read and ignore
printf("you entered %d \n",numinput);
printf("would you like to enter another # ?");
fgets(uinput,sizeof(uinput),stdin);

Related

My command prompt wont run the whole program

This code runs perfectly in my IDE; I even tried it in an online compiler just to be sure, but when I try to open the .exe it will only ask for the integer and automatically close. I tried it with another program from the school where I asked for like 15 numbers but right before a goodbye message it just closes. Any idea how to fix cmd?
#include <stdio.h>
int main()
{
int numberOfWidgets;
printf("Give me a number: ");
scanf("%d", &numberOfWidgets);
printf("You choose the number: %d", numberOfWidgets);
return 0;
}
You need to add two lines to the end of your program:
int main() {
...
getchar();
getchar();
return 0;
}
The first call to getchar will clear the return key you pressed when you entered the number, the second one will stop and wait for a key to be pressed.
That way, your program will not exit until you press a key, and you will be able to read the output.

How to repeat a process in a while until enter is pressed?

I need to repeat a process and I'm using a while. I need to do antoher process when enter key is pressed and I'm using if(getchar()). The problem is that the while "pauses" when it gets to the if because it's checking if getchar() it's true. I need to know how to keep looping the while whithout it stopping to check if there's an enter.
I'm making a game in which you have 1 minute to guess as much names as you can. So the purpose of the while() is to countdown from 60 to 0 seconds (clears the screen and prints the new second and the name you're actually guessing every second). So I want it to keep running the while() so the timer keeps running, but if enter is pressed it only changes the guessed name to a new name and the timer keeps running. (I don't know if I was clear but this is the idea)
//program in c
while(//specific condition)
{
/*- here goes the code for a timer that every second it clears the
- terminal and prints the next number (in seconds).
-
-
-*/
if(getchar()) //the current program stops here and keeps running the loop
//until enter is pressed
{
//second process
}
}
I expect the while to keep looping until there's an enter. When that happens I want it to enter the if, exit the if and keep looping.
char buffer[100];
while (fgets(buffer, sizeof(buffer), stdin))
{
if (strlen(buffer) == 1)
break;
if (sscanf(buffer, "%f", &f) == 1)
{
total += f;
printf("Enter another number: ");
}
}
if you have conio.h available in your environment you can use kbhit
while(//specific condition)
{
/*--process to do
-
-
-
-*/
if(kbhit())
{
if (getchar() == 0x0d)
{
break;
}
}
//second process
}
In this loop, the second process will run without checking the enter key and only exit if enter key is pressed.
You cannot use if(getchar()=='\n')
so the program runs until an enter key is pressed
because buffer value of '\n' will be present and it'll alter the next iteration
char a;
printf("Enter charecter or press enter to exit:");
scanf("%c",&a);
while(1)
{
//process 1 loop
if (a == '\n')
{
// process 2 here, if process two has loop make it's own loop here
printf("we are in process 2\n");
break;
}
getchar();
printf("Enter charecter or press enter to exit:");
scanf("%c",&a);
}
You did't give enough code to understand what input stream you are working with but something like this will do it, if it's file stream or string do it accordingly by replacing scanf with fgets, or file stream inputs like fscanf or fread.

why is printf not called when expected?

This is my Code [Note: I am using Eclipse for C/C++ on Windows Platform]
#include <stdio.h>
#include<stdlib.h>
int main(void) {
int num;
printf("Enter a number:\n");
scanf("%d",&num);
if(num%2==0)
printf("Number is Even");
else
printf("Number is Odd");
return EXIT_SUCCESS;
}
Here I have to enter an Integer first only then printf is called... I want to call printf first before I enter an Integer...What am I doing wrong here?
for example this is the output that I get
6
Enter a number:
Number is Even
and expected output is
Enter a number:
6
Number is Even
you can call fflush(stdout) after first printf to print the buffered output. But considering in future if you extend the program with more printfs then adding fflush after every printf will be an overhead. So you can add
setbuf(stdout, NULL)
just before all the printfs.
This will make sure no output is buffered and you will see the prints instantaneously.

First letter of any word after the first goes missing

I am fairly new to programming and i have done some in school, but they only taught basic functions like printf, scanf, for, while, pointers. I am making a small program that will print user input in to a file, but when the text is written into the file the first letter of every word after the first is missing and i don't know why. can somebody explain what is happening to the first letters and do so in a simple manner if you can, please and thank you for your answer.
This is the function i am using to write to the file.
void text(){
int e=1;
puts("After a sentance press enter to continue or esc to stop");`
printf("Enter text now\n");
FILE *fp;
fp=fopen("Text.txt","w");
End:while(e==1){
char txt[100];
puts(gets(txt),fp);
if(getche()=='\e')
e=0;
goto End;
} //end of while
fclose(fp);
}// end of function
New code
void text(){
int e=1;
puts("After ending a sentance press enter to continue or esc to stop");
printf("Enter text now\n");
FILE *fp;
fp=fopen("Text.txt","w");
while(e==1){
char txt[100];
fgets(txt,100,stdin);
fwrite(txt,sizeof(char),sizeof(txt),fp);
if(getche()=='\e'){
break;
}
else;
}
fclose(fp);
}
Your code has many issues, but... your particular problem is that getche() reads one character, if it is \e you do something, but if it is another characters, then it is lost!
Using your functions of choice (getche() and gets()) you can do:
while (1)
{
char c = getche();
if (c == '\e')
break;
txt[0] = c;
gets(txt+1);
/* ... */
}
This will not remove the first character, but will fail with empty lines, I think.. I will leave that as an exercise to the reader.

Getting the prompt from the remote terminal over ssh

I have a simple program test which gets a number as input and prints the same on console.
#include<stdio.h>
int main(void)
{
int i;
printf("Test Pgm \n");
printf("Enter a no:");
scanf("%d",&i);
printf("No Inputted:%d \n",i);
return 0;
}
//The above program lies on 10.220.5.xx (different machine)
##gcc -o test test.c
On invoking the test pgm frm another machine over ssh , I don't get any prompt on the machine where im executing.
$ ssh user#10.220.3.xx '/home/user/test'
user#10.220.3.xx's password
After entering the password i don't get see anything not even 'Test Pgm'. How do i get the prompt remotely and input the values?
Try adding fflush(stdout); before the scanf().
Also, you must check the return value of scanf(), it can fail to convert the input if given non-numerical text:
fflush(stdout);
if(scanf("%d", &i) == 1)
printf("Number input: %d\n", i);

Resources