IT, Programming, & Web Development › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 3: [Algorithms] – Linear Search, Binary Search, Bubble Sort, Selection Sort, Recursion, Merge Sort › Working outside CS50 IDE: Hurdle with scanf command
Tagged: scanf, scanf in c
- This topic is empty.
-
AuthorPosts
-
March 30, 2022 at 11:17 am #311
Since CS50 IDE not loading on my desktop, I thought to use some other free online IDE. Came to know about GeeksforGeeks and decided to use it. I know functions like get_int not possible as without cs50.h library.
Here is the program I wrote ( https://ide.geeksforgeeks.org/lPoZXRZntH ).
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”yes” line-numbers=”yes” bg-color=”#abb8c3″ theme=”dark” language=”clike” wrapped=”yes” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
#include<stdio.h> int main() { int t = 5; int num[t]; for(int i = 0; i < t; i++) { printf("enter"); scanf("%d",&num[i]); printf("%d",num[i]); } }
[/dm_code_snippet]
I expected a screen to appear with “enter” after which I will put 5 numbers one by one. But instead, getting a strange output:
enter272491544enter32765enter15775231enter0enter1h
Here is how it worked for me:
Reply
I don’t quite understand what is your question. The code is working as it should. For each interaction of the for loop, it prints “enter”, and allow you to enter a number, and prints this number after and repeat.
If you don’t want to repeat the “enter”, put the first printf outside the loop. If you think it’s strange all in the same line, you have to use “\n” on printf to print a newline.
As said, the program seems to work as intended. However, I was able to reproduce a similar output to yours by entering garbage data as input. You have no control of the user input here. I would suggest you add some kind of verification that the entered number is actually a number 🙂
OP
Still not clear as I am not finding any prompt space to enter input.
The below command should prompt a space to enter input!
scanf(“%d”,&num[i]);
So how without entering any input, getting output.
Reply
I don’t really know what you mean by that.
scanf
doesn’t prompt, or display anything, it just reads standard input.What I think you’re interpreting as a “prompt” is just the side effect of the fact that you would normally be running your program in a terminal, which displays your input in-line with your output. That only happens because your standard input on a terminal is you typing directly into it. If your standard input is coming from somewhere else (such as a file, which is likely how that site does it) then your input won’t be displayed along with your output because your input and output are not rolled into a single source like they are in a terminal.
OP
This is a difference between running your program in a terminal and not running your program in a terminal.[learn_press_profile]
-
AuthorPosts
- You must be logged in to reply to this topic.