473,395 Members | 1,679 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Simple C program not running as expected

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <conio.h>
  3. #include <string.h>
  4.  
  5. struct Book {
  6.            char title [200];
  7.            char Author_name [200];
  8.            int eidtion ,year;
  9.            };
  10.      struct Book b[100];
  11.      static int i =0;
  12.  
  13. int add_info ();
  14.  
  15. int main(){
  16.         int opt=1;
  17.         while (opt !=0){
  18.         printf("\n1. Add book information :");
  19.         printf("\n2. Display list of books :");
  20.         printf("\n3. book information :");
  21.         printf("\n4. Add book information :");
  22.         scanf("%d" ,&opt); 
  23.  switch (opt){
  24.         case 1:{
  25.      add_info (); 
  26.      break;
  27.      }
  28.  
  29.   }
  30.   }
  31.           return 0;            
  32. }
  33.  
  34. int add_info (){
  35.      //gets(b[i].title);
  36.      printf ("Enter Book title :");
  37.      gets(b[i].title);
  38.      printf ("Enter Author name :");
  39.      gets(b[i].Author_name);
  40.      printf ("Enter Book eidtion :");
  41.      scanf("%d",&b[i].eidtion);
  42.      printf ("Enter Year of eidtion :");
  43.      scanf("%d",&b[i].year);
  44.      i++;
  45.      return 0;
  46.      }
//as I run this program gets(b[i].title); has not executed .output on is like *** Enter Book title : Enter Book eidtion : _ both statements got printed .not asked to input in varaible b[i].title. when I used line( commented now )then it run ture manner
Jul 2 '11 #1
7 2362
weaknessforcats
9,208 Expert Mod 8TB
scanf stops scanning when it encounters a character tht doesn't match the type you are scanning for. In your case it looks like the enter key you used in one scanf is still in the input buffer when you reach the next scanf. That causes the second scanf to return without doing anything.

Be sure to to a getch after each scanf to remove that enter key.
Jul 2 '11 #2
whodgson
542 512MB
....also B Stroustrup recommends that C programmers should never use gets() and "consider it poisoned". ref pp1018 Programming Principles and Practice using C++.
Jul 6 '11 #3
It is better you flush the standard input before you take the input form the user as

Gets reads characters from stdin and stores them as a string into b[i].title until a newline character ('\n') or the End-of-File is reached. So when it goes to read the input for the "Enter Book title :", it already find a previously stored '\n' in keyboard buffer and accepts it.

printf ("Enter Book title :");
fflush(stdin);
gets(b[i].title);
Jul 9 '11 #4
weaknessforcats
9,208 Expert Mod 8TB
Unfortunately, you cannot flush an input stream because you cannot tell how much input there is. Not all of it may be entered yet.

Also, gets() converts the \n in the input to a null in the buffer hoilding the string so there is no null to trip over later.

The real problem with gets() is that you cannot know how much input will be read until a \n is encountered. And that means you cannot know how large a buffer you need to store the string. If you overrun the buffer you have corrupted memory and you will crash.
Jul 11 '11 #5
Yes weaknessforcats I agree with you on

"The real problem with gets() is that you cannot know how much input will be read until a \n is encountered. And that means you cannot know how large a buffer you need to store the string. If you overrun the buffer you have corrupted memory and you will crash"

but what if I flush the buffer before presenting the message to the user to enter any input. For example

fflush(stdin);
printf ("Enter Book title :");
gets(b[i].title);

I think this will pickup the user input as is not the undesirable ones...
Jul 11 '11 #6
weaknessforcats
9,208 Expert Mod 8TB
I say again you cannot use fflush to flush in input stream.

fflush can only flush your output buffer. If you use it in an input buffer, the results are undefined. Therefore, fflush(stdin) is an error.

Input streams need to be processsed and the functions that process an input stream all presume that you know what data is coming before it is entered. That is, you wil have formatted input. Now gets and scanf and the other f functions will behave correctly.

If you do not know what will be entered, then you must fetch a character at a time and make a decision for that character as to keeping it or discarding it. This can be a lot of work. So unless you are writing some professional code, stick with formatted input. That will mean that you don't need to clear out your input buffer because there will be nothing unexpected there.
Jul 12 '11 #7
What if I say

while ((ch = getchar()) != '\n' && ch != EOF);

instead of fflush.
Jul 12 '11 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: NetMasker | last post by:
Using VB.NET 2003 I want to keep a program running and waiting for users' input without using a Form that loads at program execution. Can I do it using just one Module or what? Is this possible or...
2
by: javaBeginner | last post by:
I need to create a simple program launcher which runs off of cd and launches a program off of the cd. It must also check the values in an ini file. The launcher program must run on all versions...
8
by: Chris Thunell | last post by:
I have created a VB.net windows forms application. If I have the program running and then I mistakenly click on my desktop icon again, I get a second instance of the program running. Is there...
14
by: tasheeta | last post by:
In my simple program I am getting this error..please help I am trying to find integers where 65537i + 3551j = 1 error: cannot convert `__complex__ int' to `long int' in assignment ...
1
by: steve smith | last post by:
Hi I have just downloaded the Borland C# Builder and the Micorsoft ..Net framework SDK v1.1 from the borland webist, and i am trying to get a simple program to run, however I keep getting errors,...
6
by: academic | last post by:
I want to compile a simple c program. Not c++ Not even Windows. Just a simple program to run in a DOS window. In vs2005 what type of project to I use. I can't get started. I tried a couple...
14
by: William LaMartin | last post by:
If I have a Windows application with no form--only a module that starts with sub main and which has a system timer, in the elapsed event of which I want to run some code, how can I keep this...
13
by: hn.ft.pris | last post by:
Hi: I have the following simple program: #include<iostream> using namespace std; int main(int argc, char* argv){ const double L = 1.234; const int T = static_cast<const int>(L); int arr;
3
by: sosoatjava | last post by:
How can a simple program be kept running until a defined control character, say "x" or menu choice 4 is entered? I can prompt a menu, offer choices, take keyboard input, perform a calculation but...
4
by: Break2 | last post by:
I am trying to write a simple program which asks a user to enter 5 integers after which the average will be computed and written to the screen. That simple. However I want to do it according to a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.