• 0

what is the difference between these two programs?


Question

What is the difference between these two programs. I read in a book that the first method is better but isn't there larger use of memory?

First

#include<stdio.h>
#include<string.h>
int main()
{
	char line[100];
	int value;
	printf("Enter the Number to be doubled : ");

	fgets(line,sizeof(line),stdin);
	sscanf(line, "%d", &value);

	printf("The double of the number is %d \n",2*value);
	return(0);
}

Second

#include<stdio.h>
#include<string.h>
int main()
{
int value;
printf("Enter the value\n");
scanf("%d",&value);
printf("The double of the number is %d",2*value);
}

8 answers to this question

Recommended Posts

  • 0

Some people seem to think that fgets is inherently safer, personally I have strong doubts about it. In any case the first program also uses scanf and does no validation on the input before calling scanf; it doesn't validate that fgets nor scanf succeeded, so it's just as terribly error-prone as the second one. And, as you mention, the first one also uses 100 extra bytes on the stack for nothing.

I suppose the point of using fgets before scanf is to do some kind of validation... which doesn't happen here.

Edited by Dr_Asik
  • 0

Neither is a good example. In the first you're allocating 100 bytes on the stack for a integer value which is probably a maximum of 4 bytes. And the second example you're at the mercy of the user as you're hoping they enter a valid integer.

As far as I'm aware fgets() is used to ensure you don't retrieve more bytes than you can store in a buffer. This provides some validation but in no way shape or form ensures the user has entered a valid value.

  • 0

ok.. let's assume that we used 4 bytes in line char..

so now is it better than the second one..?

in the first program we two functions to get the input whereas in the second one we only use one function for storing the input.. isnt it better now?

plus what is the difference between scanf and sscanf??

  • 0

As I said, both programs are very error-prone because both scanf and fgets can fail and neither checks for that. If you need safe input, it's pretty complicated in C... IMO any input in a C program should be debugging purposes, if you need reliable, end-user input, use a better programming language like Java, Python, C# or whatever. (or take the time to learn it properly in C : http://www.friedspace.com/cprogramming/safeinput.php more nice advice at http://www.daniweb.com/tutorials/tutorial45806.html#)

I suggest you read the description of these functions here:

fgets

scanf

sscanf

It's when you have to deal with this stuff that you realize how pathetic C is for general application programming; it's a thin, thin layer over assembly, nothing else, you're still coding tons of error-prone, complicated logic for the most basic tasks. Anyway I disgress.

Edited by Dr_Asik
  • 0
I read in a book that the first method is better

Well, what reason does the book give?

Neither is a good example. In the first you're allocating 100 bytes on the stack for a integer value which is probably a maximum of 4 bytes.

He's allocating 100 bytes for a string representation of a character, which could easily exceed 4 bytes. 4 bytes is if the integer is stored as an integer, and for that, he is already allocating exactly 4 bytes on the stack.

Not that 100 bytes on the stack means that much. Yes, it's a bit more memory, but this is the stack, not the heap, and the stack is pre-reserved and often pre-committed at the start of your thread (this could vary by OS, of course), so unless this pushes you past the range of committed pages on the stack, it doesn't matter one bit if you allocate 1 byte or 1000 bytes.

plus what is the difference between scanf and sscanf??

Read the documentation.

Although the specifics vary from implementation to implementation, generally speaking, sscanf is implemented using scanf or vice-versa. In the Windows CRT, for example, sscanf just creates a dummy stream from the string and passes all that along to scanf. For the book to say that fgets+sscanf is somehow inherently better than scanf suggests ignorance on the part of the book's author. Unless you have a specific need to work with the string--perhaps to do additional custom processing or checking before running the scanf--there is no point in doing what the author is suggesting. In either case, you'll need to do input checking--you can't escape that.

  • 0
It's when you have to deal with this stuff that you realize how pathetic C is for general application programming

:p Not that a lot of general application programming these days operate on console input...

Edit: Okay, I see his thread about doing network in C. Oh, that oughta be fun...

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • You pay just $100 per TB with this rare 4TB PCIe Gen4 NVMe SSD deal by Sayan Sen SSDs and GPUs are incredibly hard to get nowadays due to high pricing. Discounts are quite rare which is why we report on them as soon as we spot a good deal. For example AMD's new 9070 GRE was finally up for sale at a very good price of just $500 thanks to a special coupon. Sadly that deal is gone but if you happen to be looking for a 4TB NVMe SSD and can spend around $400 there is a really good offer on sale that you should not miss out on as TeamGroup's 4TB G50 model is on sale for that that price which means you are only paying $100 per TB, a very good deal in the current market (purchase link under the specs table down below). The TeamGroup T-FORCE G50 NVMe SSD is a PCIe Gen4 drive and as such it promises to deliver sequential read speeds of up to 5,000 MB/s, helping accelerate game loading, file transfers, and everyday computing tasks. Since this is a 4TB drive you can use it for a gaming library to take advantage of things like DirectStorage. The SSD features an InnoGrit controller and SLC caching technology to support consistent performance. An ultra-thin, patented graphene heatsink is included to aid in heat dissipation. Get it at the link below: Team Group T-FORCE G50 4TB Internal SSD (TM8FFE004T0C129): $449.99 + $50 off w/ promo code SSF69668, limited offer => $39.99 (Sold and Shipped by Newegg US) Good to know This Amazon deal is U.S. specific, and not available in other regions unless specified. We only use first-party seller links (at the time of article publishing); ensure that you purchase from a first-party seller link only. Check out Today's Deals on Amazon | or our recent tech deals. Become a Prime member (for Students or SNAP) via Neowin Get Prime Access - Prime for half price (for qualifying Medicaid, EBT, SNAP) Subscribe to Prime Video, Audible Plus, Music Unlimited or Kindle Unlimited via Neowin As an Amazon Associate, we earn from qualifying purchases.
    • I agree. I also think Phil stayed too long. They should definitely fire whoever thought all a console platform needed was Call of Duty, Elder Scrolls, and Fallout to survive. Asha and crew are still saying they need more Elder Scrolls and Fallout games. They simply don't get it.
    • Macbook Air is an appealing option, as are plethora of Windows devices with various different CPU's
    • Mozilla highlights Firefox Nova 2026 redesign and more upcoming features with new roadmap by Sayan Sen Last month Mozilla confirmed that Firefox was set to get a major redesign this year. Dubbed "Project Nova", it can already be tested and will roll out to all users later this year.The idea is to keep the browser competitive in a rapidly evolving internet landscape. As such the revamp focuses on improving privacy, usability, performance, accessibility, and customization. Key privacy features including the built-in VPN, private browsing mode, and Enhanced Tracking Protection, will be more visible and easier to manage, while users will have the option to disable AI features entirely through a dedicated kill switch. Additionally, the redesign promises faster page loading, the return of Compact mode, expanded personalization options, and stronger accessibility support. You can find the full details in the dedicated piece linked above. In a new blog post today the company once again reiterated on Nova and also emphasized other new and upcoming features like the settings revamp that is intended to make it easier for users to understand browser settings. In order to make it simpler for users to keep up with such features Mozilla today is launching Firefox roadmap. Hence enthusiasts and interested users will be able to check out what's cooking and also share feedback about the upcoming additions. Alongside the roadmap announcement, Mozilla also highlighted what's new in Firefox 152. One of the biggest additions is the arrival of Tab Groups on Android. The feature, which has already been helping desktop users organize large numbers of tabs, is now beginning to roll out on mobile. Users will be able to group related tabs together, assign names and colors to them, and return to them later. Mozilla says support for iOS will arrive later this year. Firefox 152 also introduces the aforementioned redesigned Settings experience. The company says the changes are meant to make controls easier to find and help users discover features they may not have previously known about. Existing preferences are not changing, though they are now better organized. Another notable addition is the new Blocked Tracker Widget, which provides a visual overview of Firefox's privacy protections by showing how many trackers have been blocked over time and the types of tracking activity the browser has stopped. Looking ahead, Mozilla revealed several upcoming roadmap features. They include customizable keyboard shortcuts, as well as enhanced PDF editing tools that will allow documents to be split, merged, and reorganized directly within Firefox. The company is also working on bringing Multi-Account Containers into the native Firefox experience thus removing the need for a separate extension. Meanwhile Firefox's built-in VPN is set to expand to mobile devices. Mozilla is also developing AI-powered features like Quick Answers, which can provide concise responses to voice queries, and Smart Window, its optional AI browsing experience that is now available without a waitlist. Finally, a new Power Saving Mode is in the works and will help reduce the impact of resource-heavy tabs on mobile devices in order to extend battery life. The video below summarizes the upcoming changes in an easy to understand format: You can find the announcement blog post here on Mozilla's official website.
  • Recent Achievements

    • One Year In
      Console General earned a badge
      One Year In
    • One Year In
      Twozo Technologies earned a badge
      One Year In
    • One Month Later
      Twozo Technologies earned a badge
      One Month Later
    • Week One Done
      Twozo Technologies earned a badge
      Week One Done
    • Veteran
      branfont went up a rank
      Veteran
  • Popular Contributors

    1. 1
      +primortal
      513
    2. 2
      +Edouard
      196
    3. 3
      PsYcHoKiLLa
      109
    4. 4
      Steven P.
      89
    5. 5
      Nick H.
      71
  • Tell a friend

    Love Neowin? Tell a friend!