• 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

    • Same Internet Archive seemed to grab the new version https://web.archive.org/web/20...d/Setup_MakeMKV_v1.18.4.exe Here's the link to an additional file it periodically downloads https://web.archive.org/web/20260213092148/https://www.makemkv.com/sdf.bin I think update's keys, etc. To manually trigger this update, put the sdf.bin file in the root of where the program is installed. When you launch the program it will pick up the file and import it. Typically put it here: C:\Program Files (x86)\MakeMKV\sdf.bin
    • Windows 11 KB5094126, KB5093998 bugging out Office apps but it may not be Microsoft's fault by Sayan Sen Microsoft last week released Windows 11 KB5094126 and KB5093998 as the latest Patch Tuesday updates. Following that the company also published the accompanying dynamic updates under KB5094149, KB5095971, and KB5094156. Although the tech giant did not acknowledge any major problems, some users online reported various issues ranging from OneDrive and Dropbox access problems, BitLocker recovery lockouts, to blue screens and BSODs. You can read about them in this dedicated piece. While there is still no confirmation about those problems from Microsoft the company has admitted to another bug which we did not report on. The tech giant has confirmed it has received reports of an issue in which certain third-party applications may be unable to launch Microsoft Office apps or open Office documents after installing the Patch Tuesday. This affects both Windows 11 as well as Windows 10. The company says the problem impacts a subset of applications that rely on OLE (Object Linking and Embedding) automation to communicate with Microsoft Office programs. According to Microsoft, affected scenarios involve third-party software attempting to open Office applications or documents from within their own interface. In such cases, the Office program may fail to launch altogether, or the requested document may not open. Oddly there may not be any error message, which probably makes the issue difficult to diagnose. The bug affects several Office products, including Word, Excel, PowerPoint, Access, and other apps in the Microsoft Office suite when they are launched through the affected software. These include tax and accounting software such as CCH Engagement and Workpaper Manager, dental practice management solutions like Dentrix and Softdent, as well as the popular research and reference management tool Zotero. Microsoft adds that other applications using similar Office integration methods could also experience the same problematic behavior. To understand the issue it is important to look at OLE, the Microsoft technology involved. OLE allows different applications to work together and share data, while its Automation feature lets one program control another. Thus this enables third-party software to launch Microsoft Office apps, open documents, and perform tasks automatically without requiring users to switch between programs. Because many accounting, healthcare, research, and business applications rely on OLE automation to interact with Word, Excel, PowerPoint, and other Office apps, any disruption can break those workflows. As a result, affected software may be unable to open Office documents or launch Office applications even though the programs themselves continue to work normally. At the moment the company has not provided a permanent fix though it has confirmed that engineers are actively working on a resolution, which will be delivered through a future Windows update. As such additional details will be shared once more information becomes available. In the meantime, Microsoft recommends a simple workaround for affected users whic is to open the Office application or document directly rather than launching it through the third-party program. For enterprise customers and organizations managing larger deployments, Microsoft says an additional mitigation is available. Admins experiencing the problem on their managed devices are advised to contact Microsoft Support for business to obtain and apply the workaround.
    • It saddens me when cars are such dull colours now. Mine is bright metallic blue and I absolutely adore it for standing out in contrast to that depressing backdrop of traffic.
    • Sparkle 2.20.0 by Razvan Serea Sparkle is a free, open-source Windows optimization tool designed to make your PC faster, cleaner, and more private. With Sparkle, you can easily debloat Windows by removing unnecessary apps and services, disable Microsoft tracking to enhance privacy, and apply performance tweaks to boost speed. Its cleaner removes junk and temporary files, while every change is safe and fully reversible. Sparkle also features a modern, user-friendly interface with automatic updates, making system maintenance simple. Explore over 39 tweaks, from disabling telemetry and hibernation to optimizing network and game settings, all aimed at customizing and enhancing your Windows experience. Sparkle supports Windows 10 and 11. Sparkle 2.20.0 changelog: Debloat Tweak has animated border New homepage loading UI New Tweak Modal (Markdown Supported) Refactored GPU Detection Added Tests with vitest Added foobar2000 to apps Added Localsend to apps Updated Modal Styles Added styles for disabled inputs Added Animated Border to debloat-windows tweak Bumped dependencies Refactor System info logic for speed Tweak info modals now support Markdown Added Clear System info cache to settings Redesigned Home Page Loading UI Changed Some Icons around the app Download: Sparkle 2.20.0 | Portable | ~100.0 MB (Open Source) Links: Sparkle Website | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • lol it was a typo, fixed! haha imagine an actual 4TB Gen4 NVMe for $40 in 2026
  • Recent Achievements

    • Reacting Well
      Dys Topia earned a badge
      Reacting Well
    • Conversation Starter
      NovaEdgeX earned a badge
      Conversation Starter
    • One Year In
      Console General earned a badge
      One Year In
    • Week One Done
      Twozo Technologies earned a badge
      Week One Done
    • One Month Later
      Twozo Technologies earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      517
    2. 2
      +Edouard
      184
    3. 3
      PsYcHoKiLLa
      106
    4. 4
      Steven P.
      88
    5. 5
      ATLien_0
      68
  • Tell a friend

    Love Neowin? Tell a friend!