LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 04-20-2005, 04:55 AM   #1
njeri
LQ Newbie
 
Registered: Apr 2005
Location: kenya
Posts: 1

Rep: Reputation: 0
gets() function in C programming


i hav a problem with the gets() function in my program code.please give me ideas.

void function3()
{
char input[50]; //The entered string
int choice,i,flag=0,count=0,count1=0,count2=0,count3=0;
printf("Enter your sentence\n");
gets(input);



when i run the program,it doesnt allow one to enter the sentence,it skips to the next line.Here is the entire program.




#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>

#define BUFFERSIZE 128
#define FALSE 0
#define TRUE 1
#define MAXIMUM 200
#define MAX 50

void function1();
void function2();
void function3();
void function4();

main()
{
time_t start, stop;
struct tm *now,*end;
char buf1[BUFFERSIZE];
char buf2[BUFFERSIZE];
char *starttime_format ="Program start time was %I:%M:%S %p.\n";
char *stoptime_format ="Program end time was %I:%M:%S %p.\n";
double elapsetime;
int choice,exit=0,count=0,count1=0,count2=0,count3=0;
time(&start);
now = localtime(&start);
strftime(buf1,sizeof buf1,starttime_format,now);

do
{

printf("==========================\n");
printf("1-Program 1:Prime numbers\n");
printf("2-Program 2:Word rotation\n");
printf("3-Program 3:Case conversion\n");
printf("4-Program 4:Print calendar\n");
printf("5-Exit\n");
printf("==========================\n");
printf("Enter your choice:\n");
scanf("%d",&choice);

switch(choice)
{
case 1: count++;
function1();
break;

case 2:count1++;
function2();
break;

case 3:count2++;
function3();
break;

case 4:count3++;
function4();
break;

case 5: exit=1;
break;

default: printf("Invalid choice\n");
break;

}
if(exit==1)
break;
printf("\n\n");
}while(exit==0);

printf("\n\n");
time(&stop);
end= localtime(&stop);
strftime(buf2,sizeof buf2,stoptime_format,end);
puts(buf1);
puts(buf2);
elapsetime=difftime(stop,start);
printf("Program run time was %.2f\n",elapsetime);
printf("Selection 1 was used %d time(s)\n",count);
printf("Selection 2 was used %d time(s)\n",count1);
printf("Selection 3 was used %d time(s)\n",count2);
printf("Selection 4 was used %d time(s)\n",count3);
return 0;
}

void function1()
{

int number,divisor, prime;
int limit=10;

for(number=2;number<=200;number++)
{
prime=TRUE;

for(divisor=2;divisor<=10;divisor++)
if(((number%divisor)==0) && number!=divisor)
prime=FALSE;

if (prime && number!=1)
{
while(number>=limit)
{
printf("\n");
limit+=10;
}
printf(" %d",number);
}
}
printf("\n");
}

void function2()
{
char name[50],hold,hold2;
int firstchar=0,lastchar,number,inputlength,n,loop;

printf("Enter words less than 50 characters\n");
scanf("%s", &name);

do
{
inputlength = strlen(name);
printf("Enter a value less than %d\n",inputlength);
scanf("%d", &number);
}while(number > inputlength);

lastchar=inputlength-1;

for(loop=1; loop<=number; loop++)
{
n=1;
hold=name[firstchar];
name[firstchar]=name[lastchar];
name[lastchar]=name[lastchar-1];

while(n<=lastchar-1)
{
hold2=name[n];
name[n]=hold;
n++;
hold=name[n];
name[n]=hold2;
n++;
}
}
printf("output=%s\n",name);
printf("\n");
}

void function3()
{
char input[50]; //The entered string
int choice,i,flag=0,count=0,count1=0,count2=0,count3=0;
printf("Enter your sentence\n");
gets(input);

do
{
printf("How do you want this text converted?\n");
printf("1.To upper case\n");
printf("2.To lower case\n");
printf("3.Sentence case\n");
printf("4.Toggle case\n");
printf("5.Quit\n");
printf("----------------\n");
printf("Enter your choice\n");
scanf("%d",&choice);

switch(choice)
{
case 1: count++;
for (i = 0; input[i] != '\0'; i++)
{
strupr(input);
}
printf("To uppercase:-\n");
printf("%s\n",input);
break;

case 2: count1++;
for (i = 0; input[i] != '\0'; i++)
{
input[i]=tolower(input[i]);
}
printf("To lowercase:-\n");
printf("%s\n",input);
break;

case 3: count2++;
printf("To sentence case:-\n");
printf("%s\n",input);
break;

case 4: count3++;
for (i = 0; input[i] != '\0'; i++)
{
if(islower(input[i]))
input[i]=toupper(input[i]);
else
input[i]=tolower(input[i]);
}
printf("To toggled case:-\n");
printf("%s\n",input);
break;

case 5: flag=1;
break;

defaultrintf("Wrong option\n");
break;
}
if(flag==1)
break;
printf("\n\n");
}while(flag==0);
}

void function4()
{
void printMonth(int year, int month);
int year,month;
// The user enters year and month
printf("Enter which year: ");
scanf("%d",&year);
printf("Enter month in number between 1 and 12: ");
scanf("%d",&month);
// Print calendar for the month of the year
printf("\n\n");
printMonth(year, month);
printf("\n\n");
}

// Print the calendar for a month in a year
void printMonth(int year, int month)
{
int getStartDay(int year, int month);
int getNumOfDaysInMonth(int year, int month);
void printMonthTitle(int year, int month);
void printMonthBody(int startDay, int numOfDaysInMonth);
// Get start day of the week for the first date in the month
int startDay,numOfDaysInMonth;
startDay= getStartDay(year, month);

// Get number of days in the month
numOfDaysInMonth= getNumOfDaysInMonth(year, month);

// Print calendar headings
printMonthTitle(year, month);

// Print body of the calendar
printMonthBody(startDay, numOfDaysInMonth);
}

// Get the start day of the first day in of the month
int getStartDay(int year, int month)
{
int getTotalNumOfDays(int year, int month);
// Get total number of days since 1/1/1800
int startDay1800 = 3;
int totalNumOfDays;
totalNumOfDays= getTotalNumOfDays(year, month);


return (int)((totalNumOfDays + startDay1800) % 7);
}


int getTotalNumOfDays(int year, int month)
{
int getNumOfDaysInMonth(int year, int month);
int isLeapYear(int year);
int total = 0;
int i;

for (i = 1800; i <year; i++)
if (isLeapYear(i)==1)
total = total + 366;
else
total = total + 365;

for (i = 1; i <month; i++)
total = total + getNumOfDaysInMonth(year, i);

return total;
}

int getNumOfDaysInMonth(int year, int month)
{
int isLeapYear(int year);
if (month == 1 || month==3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
return 31;

if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;

if (month == 2)
if (isLeapYear(year)==1)
return 29;
else
return 28;

return 0;
}


int isLeapYear(int year)
{
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
return 1;

return 0;
}


void printMonthBody(int startDay, int numOfDaysInMonth)
{

int i = 0;
for (i = 0; i < startDay; i++)
printf(" ");

for (i = 1; i <= numOfDaysInMonth; i++)
{
if (i < 10)
printf("\t%d",i);
else
printf("\t%d",i);

if ((i + startDay) % 7 == 0)
printf("\n");
}

printf("\n");
}


void printMonthTitle(int year, int month)
{
void getMonthName(int month);
printf(" ");
getMonthName(month);
printf("\t%d\n",year);
printf(" --------------------------------------------------------\n");
printf(" \tSun\tMon\tTue\tWed\tThu\tFri\tSat\n");
}


void getMonthName(int month)
{
char monthName;
switch (month)
{
case 1:
monthName=printf("January");
break;

case 2:
monthName=printf("February");
break;

case 3:
monthName=printf("March");
break;

case 4:
monthName=printf("April");
break;

case 5:
monthName=printf("May");
break;

case 6:
monthName=printf("June");
break;

case 7:
monthName=printf("July");
break;

case 8:
monthName=printf("August");
break;

case 9:
monthName=printf("September");
break;

case 10:
monthName=printf("October");
break;

case 11:
monthName=printf("November");
break;

case 12:
monthName=printf("December");
break;

default:
printf("Invalid Month name\n");
break;
}
}
 
Old 04-20-2005, 05:38 AM   #2
scuzzman
Senior Member
 
Registered: May 2004
Location: Hilliard, Ohio, USA
Distribution: Slackware, Kubuntu
Posts: 1,851

Rep: Reputation: 47
As far as I know, gets() returns a string up until the first whitespace character doesn't it?
 
Old 04-20-2005, 05:41 AM   #3
XavierP
Moderator
 
Registered: Nov 2002
Location: Kent, England
Distribution: Debian Testing
Posts: 19,192
Blog Entries: 4

Rep: Reputation: 475Reputation: 475Reputation: 475Reputation: 475Reputation: 475
Moved: This thread is more suitable in Programming and has been moved accordingly to help your thread/question get the exposure it deserves.
 
Old 04-20-2005, 06:14 AM   #4
Vookimedlo
Member
 
Registered: Jul 2004
Location: Czech Republic - Roudnice nad Labem
Distribution: Debian
Posts: 253

Rep: Reputation: 34
Hi,

it's caused by input buffer and scanf function, which doesn't take newline char form buffer. So you need to remove all remaining chars.

You can do it simply like this:

Code:
printf("==========================\n");
printf("1-Program 1:Prime numbers\n");
printf("2-Program 2:Word rotation\n");
printf("3-Program 3:Case conversion\n");
printf("4-Program 4:Print calendar\n");
printf("5-Exit\n");
printf("==========================\n");
printf("Enter your choice:\n");
scanf("%d",&choice);

 while(getchar() != '\n'); /*clear buffer*/

Never use gets function, because it's security risc . Use fgets instead.

Code:
void function3()
{
char input[50]; //The entered string
int choice,i,flag=0,count=0,count1=0,count2=0,count3=0;
printf("Enter your sentence\n");
 
fgets(input,49,stdin);
 
Old 04-20-2005, 06:16 AM   #5
kees-jan
Member
 
Registered: Sep 2004
Distribution: Debian, Ubuntu, BeatrIX, OpenWRT
Posts: 273

Rep: Reputation: 30
I'm not sure what to say. If you post a program of this magnitude, it would be much appreciated if you improved readability (i.e. indentation and stuff).

Your problem is not with the gets(). It is with your use of scanf. Your code reads
Code:
 scanf("%d",&choice);
which, in and of itself, is fine. What it does, however, is allow you to type some data, including a newline. Then, it starts intepreting. As soon as it finds a number, interpretation stops. I.e. The newline character you type behind the number is not processed by your progam (yet).
Then, when you call gets(), it processes all remaining data (including the newline you already entered), without allowing you to enter new data.

There are a few ways to work around this. I'm not sure which one will work for you / which one you'll prefer.
  • use gets() in combination with sscanf() to read menu input
  • read menu input with scanf("%d\n", &choice) to also read the terminating newline
  • call gets() twice, once to read the newline from the previous menu selection, once to retrieve the actual data

Groetjes,

Kees-Jan
 
Old 04-20-2005, 06:17 AM   #6
mehuljv
Member
 
Registered: Nov 2004
Posts: 72

Rep: Reputation: 15
hi,
gets() returns string up untill it finds "\n" , white spaces are allowed. before scanning the test you flush the input buffer. say using fflush(stdin) this should work.

Regards
Mehul
 
Old 04-20-2005, 06:22 AM   #7
mehuljv
Member
 
Registered: Nov 2004
Posts: 72

Rep: Reputation: 15
if you want to read a string including space then use following scanf option,

scanf("%[^\n]s",str);

this will read the string including space

Regards
Mehul
 
Old 04-20-2005, 06:24 AM   #8
itsme86
Senior Member
 
Registered: Jan 2004
Location: Oregon, USA
Distribution: Slackware
Posts: 1,246

Rep: Reputation: 59
fflush(stdin) isn't really a recommended way to flush the input buffer since fflush() has undefined results on non-output streams (meaning it's safe for, say, stdout but not stdin.) It might work with one compiler, but do something entirely different on another.

But as long as you're going to use gets() anyway, I guess you're probably not too concerned about portability gets() is very dangerous to use. In fact, gcc even tells you that it is:
Code:
itsme@itsme:~/C$ cat gets.c
#include <stdio.h>

int main(void)
{
  char buf[10];

  gets(buf);
  return 0;
}
itsme@itsme:~/C$ gcc -Wall gets.c -o gets
/tmp/ccAJmrS0.o(.text+0x23): In function `main':
: warning: the `gets' function is dangerous and should not be used.
itsme@itsme:~/C$
fgets() is a safe alternative to gets().
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
*NIX systems programming: error using stat function MDBlueIce Programming 7 06-27-2005 06:42 AM
exec function in Linux programming geminigal Programming 5 05-06-2005 04:07 AM
A main can be changed by a function local without passing anything to the function? ananthbv Programming 10 05-04-2004 01:31 PM
Perl exec function in linux (and system-function) nazula Programming 1 04-19-2004 12:21 PM
Programming function keys dazdaz Linux - Software 14 11-04-2003 04:37 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 01:00 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration