Why is scanf printing its input in the Nios 2 IDE? - c

A very simple program is not even working.
int main ()
{
int n;
while (scanf("%d", &n) > 0)
return 0;
}
The above I would expect to only read to input but it also prints the input:
2
2
3
3
I would have expected the above behavior if I had also this line in the while loop but I don't:
printf("%d\n", n);
Can you explain?
Update
There is nothing in the answers that explain why this is happening. And no setting in the Nios 2 IDE for local echo turned on or off. And if there were it probably would not be dafeult causing unexpected output. And this program also prints its input:
#include <stdio.h>
int main ()
{
int n;
while (scanf("%d", &n) > 0)
;
return 0;
}
So this Nios 2 IDE which is based on Eclipse is nobody's choice since you cannot figure out why it is behaving in a way it shouldn't

2 candidates
Your terminal I/O has an unneeded local echo turned on. Thus an OS issue, not a issue of this program.
Missing ; at end of while() invokes expected results. The code as posted should simple read some input and then immediately exit. This is not as the OP recounts. Suspect it is a mis-transcription of the problem.
[edit] Now see all of #alk solution. Certainly something is in the OP's real code that is not visible in the post -maybe due to mixed \r and \r\n and \n?
// Was it a typo that the OP did not have a;at the end?
while (scanf("%d", &n) > 0)

Most probably your code looked like this:
int main ()
{
int n;
while (scanf("%d", &n) > 0) printf("%d\n", n);
return 0;
}
// ------------------------------------------------------------------ scroll right >>> --------------------------------------------------

scanf() returns integer which is number of parameters given as input. In your case scanf("%d",&n) returns 1.
You can check this as ref-
http://cboard.cprogramming.com/c-programming/119407-scanf-return-values.html

Related

Program works in terminal but "timed out while waiting for program to exit" in Check50

I am new to programming and this is my first time posting here so please excuse me if the answer is painfully obvious!
I encountered this error when working on pset1 from CS50x 2019. We're supposed to print a pyramid with a height between 1 and 8 inclusive, and the program needs to re-prompt the user if the height entered is out of this range.
When I ran the program in the terminal, it works as intended every time... but not according to Check50. I am wondering if there is something wrong with my code or is this more of a Check50 problem? This is my result from Check50.
Thanks in advance!
#include <stdio.h> // for printf function
#include <cs50.h> // for get_int function
#include <unistd.h> // for sleep function
int main(void)
{
// prompt user for height; reprompt if input is less than 1 or greater than 8
int h;
do
{
h = get_int("Height: ");
}
while (h < 1 || h > 8);
// outer loop prints r rows; inner loop prints c columns
for (int r = 0; r < h; r++)
{
for (int c = 0; c < h; c++)
{
if (c < h - 1 - r)
{
printf(".");
}
else
{
printf("#");
}
sleep(1);
}
printf("\n");
sleep(1);
}
}
screenshot with input 8 showing the pyramid
Converting my comment into an answer.
Are you sure the sleep(1); calls inside the for loops aren't causing the timeout?
It takes about 72 seconds to produce an 8-level pyramid, which is a tad excessive. On my machine, I don't even see each character as it is printed because there is no fflush(stdout) to force the characters to the screen (so it takes about 9 seconds per line).
Comment out the sleep() calls and there's a decent chance your code will pass the Check50 testing without a timeout.

getchar() returns a character that isn’t a newline after I press enter

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.

Why is this C for-loop not working properly?

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();

Using putchar and printf together in the same C Program?

I've written a small C program where I wanted to display the numeric ASCII value that corresponds to certain key presses.
My code follows. The problem is, after running the program, it accepts input, but doesn't do anything else. It doesn't even reach the first printf statement. I can't figure out what the issue is - is there a problem with mixing the getchar() function with the printf() function in the same program?
#include <stdio.h>
int main() {
const int numKeys = 256;
int keys[numKeys];
int i;
for (i = 0; i < numKeys; i++) {
keys[i] = 0;
}
printf("\n Start pressing some keys!\n\n");
int c;
while ((c = getchar()) != EOF) {
printf(" CAPTURED: %d\n", c);
keys[c]++;
}
printf("\n\n ** RESULTS ** \n\n");
for (i = 0; i < numKeys; i++) {
if (keys[i] != 0) {
printf(" Key with value %d was called %d times.", i, keys[i]);
}
}
}
I should clarify that I have a Windows XP Pro machine, with Cygwin installed. I use Cygwin for my development space, so I wonder if there is something different when running this type of program in that environment.
I found the problem. I think you want to use
while ((c = getchar()) != EOF && c != '\n')
Instead if you want to have it print the results after the person hits enter/return.
problem 1 : getting to printf(" CAPTURED: %d\n", c); without having to press the Enter key
solution : is by using getche() in while loop.
problem 2 : getting to 'printf("\n\n ** RESULTS ** \n\n");' or essentially breaking while loop?
solution : you cannot. you will never get EOF as long as you read from keyboard.
workaround : close stdin or use a escape character other than EOF.
EDIT : workaround2 :
->use getchar() itself. but to print those entered char u need to press Enter key. now on windows ctrl+z gives EOF but this should be the **FIRST** input on the line after you press Enter key. well this is not a good solution.
if you want a "Press key display times pressed scenario. there is just no simple way(AFAIK)"
I believe that the first printf statement gets executed, but due to buffering is not displayed on the screen immediately. Use fflush(stdout) to send the contents of the buffer to the screen. Ie:
printf("\n Start pressing some keys!\n\n");
fflush(stdout);

I'm hitting a segmentation error when I scanf(%s,lastName); (body code inside)

EDIT: About to try intilizing my chars properly... [didnt work=( ]
EDIT: SOLVED (I can't answer my own question for another 7 hours...)
Thanks for the comment Brian, that's just a constant declared at the top.. (it = 20).
It turns out the error was happening because I forgot to add a next line after I took in the input name.
it's working now =D
:ENDEDIT (lol)
I've code my code below, Basically I put in the first name this is supposed to find
John
Then I put in the last name...
Locke
and as soon as I enter in "Locke" it hits this error, I feel like maybe it's the scanf and I should be using a better alternative ???
int findPatron(struct Library *lib,struct Patron **p)
{
int i;
char firstName[NAME_LENGTH], lastName[NAME_LENGTH];
printf("\nPlease enter the patron's first name: ");
scanf("%s",firstName);
printf("\nPlease enter the patron's last name: "); //this line prints...
scanf("%s",lastName); //SEGMENTATION ERROR happens here I'm pretty sure.
printf("deerrrr"); //this line never prints
for(i = 0; i<lib->totalPatrons;i++)
{
printf("checking %s %s to %s %s",lib->patrons[i].name.first,lib->patrons[i].name.last,firstName,lastName);
if((strcmp(lib->patrons[i].name.first, firstName) == 0) && (strcmp(lib->patrons[i].name.last, lastName) == 0))
{
**p = lib->patrons[i];
return 0;
break;
}
}
return 1; //No Match!
}
You're getting the segmentation fault after your scanf() statements.
If you remove everything after printf("deerrrr"); and add a \n to that output so the buffer is flushed, you'll find that it all works just fine (provided NAME_LENGTH is at least 6 given your example input).
Part of programming is knowing how to isolate and debug your problems.
Your issues are with your loop and lib struct - you're dereferencing something you shouldn't be.
SEGMENTATION ERROR happens here I'm pretty sure
this line never prints
C's printf is buffered, and only gets flushed by an explicit call to fflush or a blocking action (like scanf, which AFAIK flushes stdout as well), so the error could happen in another place. Learn to use debugger, that's the proper way of debugging C programs.

Resources