I know the program I am posting is very basic but I am unable to find the error. I rechecked everything but despite no compilation error, the output is not coming.
#include<stdio.h>
#include <stdlib.h>
int main()
{
int i;
while(1)
{
if((scanf("%d",&i))!=42)
{
printf("%d",i);
}
else
{
break;
}
}
return 0;
}
Thank You for your time and consideration.
scanf does not return the value entered. It returns the number of inputs matched. So your check for 42 is incorrect. It will return 1 if an integer was assigned to i, or 0 if there was invalid input. If you want to exit the loop when the user enters 42, you should explicitly test if (i == 42).
As simonc mentioned, The reason you're not getting any output is because printf("%d",i); is not printing a newline "\n" after the number, and the standard out (stdout) stream is line-buffered. That means the standard library is going to continue to buffer up your printfs until a newline is encountered. At this point the buffer will be flushed to the console.
The solution is to add the newline (which is probably what you desire anyway): printf("%d\n",i); Alternatively, you could call fflush(stdout) to tell the std library to flush the buffered content to the console immediately. Or, writing to stderr will output immediately, because it is unbuffered.
This should demonstrate:
#include <stdio.h>
int main()
{
int i;
while(1) {
fprintf(stderr, "Enter a number (or 42 to quit): ");
if((scanf("%d",&i)) != 1) {
fprintf(stderr, "Invalid input.\n");
continue;
}
if (i==42)
break;
printf("Number provided: %d\n", i);
}
return 0;
}
Output:
$ ./a.exe
Enter a number (or 42 to quit): 17
Number provided: 17
Enter a number (or 42 to quit): 42
$
You are comparing the scanf function's return value to 42, not the variable i's value.
maybe you should read this
http://www.cplusplus.com/reference/cstdio/scanf/?kw=scanf
Related
I have make a program that take a number and a separator. If the user press enter, then the program will print the total of the number.
example input: 2[space]3[enter] will print "total = 5", 1[space]2[space]3[enter] will print "total = 6", but if I input 2a3[enter], the program will get terminated and exit instead of printing "error!" and the "press ENTER..." message. Previously, I use the system("PAUSE") function and there was no problem(the error message appear). And then I know that it is not standard, so I replace it with 2 lines of code(you can see it in the code) and the problem occur.
My input:
2[space]3[enter] --> print "total = 5"
2a3[enter] --> the program gets terminated instead of printing "error!" and the "press ENTER..." message
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, total;
char separator;
for(;;)
{
scanf("%d%c", &num, &separator);
total += num;
if(separator == '\n')
{
printf("total = %d\n", total);
break;
}
else if(separator == ' ')
{
//do nothing
}
else
{
printf("error!\n");
break;
}
}
printf("press ENTER to exit..."); //this
getchar(); //two lines
//previously, I use system("PAUSE"), and there is no problem.
return 0;
}
I use gcc 10.3.0 and Windows 10 OS.
Can anyone explain to me why this problem occur?
Input buffer fun.
When you hit the break; statement after the printf("error!"), there is a "3\n" in the input buffer; thus getchar() finds something to read immediately and thus your program appears to terminate immediately. The missing newline after error causes the line to be gobbled on Windows because the command prompt moves the cursor left first rather than starting the command prompt mid-line.
It is not recommended to use scanf to parse keyboard input but rather to use fgets() or getline() and parse yourself to avoid input buffer stuff like this.
Use of total like that is undefined, but it is improbable that you are using a processor that's going to fault here and I disregarded it.
#include <stdio.h>
#include <wiringPi.h>
#include <softPwm.h>
int main(void)
{
wiringPiSetupGpio();
for(int i = 0 ; i <50; i++)
{
if ( i%10 == 1)
{
printf("\n");
}
printf("%d ", i);
delay(1000);
}
return 0;
}
I'm working in rasberry pi environment.
I want to print a number for each 1 second. But this code did not print a number one by one but
print 10 numbers for each 10 seconds. This code gives 10 numbers in line at once. What's the problem??
The stdout channel is line buffered by default. This means that data sent to stdout won't necessarily appear until a newline character is printed.
If you call fflush(stdout), any buffered output will be immediately printed.
printf("%d ", i);
fflush(stdout);
in order to print the values at the running time using printf you need to add \n so try this may work.
#include <stdio.h>
#include <wiringPi.h>
#include <softPwm.h>
int main(void)
{
wiringPiSetupGpio();
for(int i = 0 ; i <50; i++)
{
if ( i%10 == 1)
{
printf("\n");
}
// a `\n` added at the end of the string!
printf("%d \n", i);
delay(1000);
}
return 0;
}
for more info read this question's answer
The problem is probably that the output stream is not being flushed. I suggest that you call fflush( stdout ); before the delay(1000); function call. This will ensure that all printed data actually becomes observable, before the program enters a wait state.
Normally, it is not necessary to explicitly flush an output stream, because the output will become visible sooner or later. For example, the output buffer will usually get implicitly flushed whenever you read input or when the program ends. Also, if your program is writing output to the user's screen (in contrast to, for example, writing output to a file), then the output stream is probably line-buffered, which means that the output stream will get implicitly flushed whenever a newline character is written.
However, in this case, it appears that the implicit flushing mentioned above is not sufficient. Therefore, you will have to revert to explicit flushing using the function fflush, as mentioned above.
This is the code:
#include <stdio.h>
int main()
{
int i = 0;
while(getchar() != '\n') {
printf("\n%d\n", i);
i++;
}
printf("second printf: %d\n", i);
return 0;
}
The expected ouput after I press enter only is:
second printf: 0
instead of:
0
second printf: 1
Why is this happening ?
I am on linux Ubuntu MATE.
So I got some information about anas firari's environment by reading his other questions. This involves some measure of physic debugging.
You are getting input of \r\n when you type a newline because your terminal is in raw mode. Older shells used to choke on this by treating \r as something that isn't whitespace, but newer ones actually work ok.
My program is supposed to exit when the user types in exit similar to how its done in a shell. First I checked online to see if syscall could be called in a loop, but then I noticed the indices of the characters in the array are wrong. Why are these changing; when I ran the program and typed in exit I had my program shoot out the 3rd index for testing purposes and it returned 'e'. So I thought it might've been flipped and flipped all values and my exit still did not work. Any thoughts on what the underlying issue may be?
#include <stdio.h>
//Abstract: This program runs a script to emulate shell behavior
#define MAX_BIN_SIZE 100
int main() { //Memory allocation
char * entry[MAX_BIN_SIZE];
while(1)
{
printf("msh>");
fgets(entry,MAX_BIN_SIZE,stdin); //Getting user input
if(entry[0]=='t' && entry[1]=='i' && entry[2]=='x' && entry[3]=='e')
{
//printf("Exiting");
exit(0); //exit(system call)
break;
printf("Inside of exit");
}
printf("msh> you typed %s %c %c %c %c",entry,entry[3],entry[2],entry[1],entry[0]); //returning user input
}
return 0;
}
I am sorry I don't have enough reputation points to add a comment, but #lundman is correct. I don't think you need to create a pointer to entry. Also, you are checking for "exit" in the reverse order. I tried and edited the code; this seems to work:
#include <stdio.h>
//Abstract: This program runs a script to emulate shell behavior
#define MAX_BIN_SIZE 100
int main()
{ //Memory allocation
char entry[MAX_BIN_SIZE];
while(1)
{
printf("msh>");
fgets(entry,MAX_BIN_SIZE,stdin); //Getting user input
if(entry[0]=='e' && entry[1]=='x' && entry[2]=='i' && entry[3]=='t')
{
printf("Inside of exit");//printf("Exiting");
exit(0); //exit(system call)
}
printf("msh> you typed %s %c %c %c %c\n",entry,entry[3],entry[2],entry[1],entry[0]); //returning user input
}
return 0;
}
int main()
{
int t, i;
int *nums;
scanf("%d", &t);
nums = malloc(t * sizeof(int));
for(i = 0; i < t; i++)
{
scanf("%d", &nums[i]);
}
printf("hey");
}
For some reason, it hangs, waiting for more input! Any ideas?
This code is correct, except for the fact that you're not freeing your memory (not a big issue for this simple code) and you're not checking scanf for errors, which may be the cause of your problem.
A better implementation with error checking and correct memory handling is described below:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int t, i, ret;
int *nums;
ret = scanf("%d", &t);
if(ret != 1)
{
/* something wrong */
}
nums = malloc(t * sizeof(int));
if(nums==NULL)
{
/* memory error */
}
for(i = 0; i < t; i++)
{
ret = scanf("%d", &nums[i]);
if(ret != 1)
{
/* something wrong */
}
}
free(nums);
printf("hey");
return 0;
}
Just a guess here...
But I'm guessing you ran it and entered :
4
1234
For example, you put in 4 and then 1234 and it hangs. Well, that would be because 1234 is the first number and not 4 distinct numbers so its waiting for the second number. You have to press enter or some such delimiter between each number.
Try this set of inputs instead:
4
1234
29
4
5
You should get :
hey
Pro grammatically, you should be checking return values from your function calls. Make sure malloc didn't return zero. Make sure scanf returns the number of inputs you expected to read. Add in printouts to make sure the values it read in are what you expected/wanted to read in.
EDIT :
Guessing you have a typo in the program which isn't displayed here. such as :
scanf("%s", &t);
Or you are getting the 'hey' and just not seeing it.
[ov#MARVIN sotest]$ ./a.out
5 5 4 3 23 1
hey[ov#MARVIN sotest]$
See the 'hey' is sort of hidden in my prompt because you are missing the '\n' new line in the printout?
Remember to flush when you are done.
In chat, OP's comments "No... BTW, if I add a printf in the loop that prints the current input, it prints everything except from the last one...". This hinted that the issue was on the final output.
The following sends data out to be printed. But stdout is typically buffered. Actual output may not occur until sometime later. Output is flushed when 1) output contains an end-of-line '\n', 2) fflush() is called 3) the program ends. I am surprised output did not appear when the program ended, but possibly OP's true code differs from the post.
printf("hey");
Change to
printf("hey\n");
Or #Cool Guy
printf("hey");
fflush(stdout);
BTW: This is also hinted in #Diversity answer.
Note: Always a good idea to check the result of scanf()
// scanf("%d", &t)
if (1 != scanf("%d", &t)) Handle_BadInput_or_EOF();