Sponsored Content
Full Discussion: making sure input are digits
Top Forums Programming making sure input are digits Post 302093650 by Corona688 on Saturday 21st of October 2006 05:32:16 PM
Old 10-21-2006
Plain ordinary scanf() isn't guaranteed to scan an entire line. %i will scan up to the point where the input stops being digits, in this case, the newline, after which standard input needs to be flushed to get rid of it.

Instead, I reccomend using fgets to input an entire line. That way there's never anything to flush.

But since you're processing the entire string byte by byte, why use scanf at all? Just check it byte by byte:
Code:
#include <stdio.h>
#include <ctype.h>

// Returns negative on error, zero or positive on success
int sum_of_digits()
{
  int sum=0;
  int n;
  char buf[512];

  // Prompt
  printf("Enter digits:  ");
  // Read in entire line into buf
  if(fgets(buf,512,stdin) == NULL)
  {
    // If couldn't read, return error
    fprintf(stderr,"Couldn't read from stdin\n);
    return(-1);
  }

  // Loop through entire string
  for(n=0; buf[n]; n++)
  {
    // If it's a newline or carriage return, stop scanning
    if((buf[n] == '\n') || (buf[n] == '\r'))
      break;

    // If it's not a digit, return error
    if(! isdigit(buf[n]))
    {
      fprintf(stderr,"Input string is not digits\n");
      return(-1);
    }

    // Add value of digit to sum
    sum += (buf[n]-'0');
  }

  // Return sum
  return(sum);
}

int main()
{
  while(1)
  {
    int val=sum_of_digits();
    if(val < 0)
      break;

    printf("Sum of digits is %d\n",val);
  }

  return(0);
}

 

9 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

making a .sh wait for user input

I need a script to halt at the end and wait for the user to hit a key...could be any ket or enter. I know it can be done but I am just starting out.. Thanks (9 Replies)
Discussion started by: verystupid
9 Replies

2. UNIX for Dummies Questions & Answers

Only Digits as input

Hi All, I am new to shell script. I wrote a very small script that takes only digits as input- but there is some problem in that.can you help me in debugging that. #!/bin/ksh echo "Digits as input" read number digit='eval ' if ] then echo "Entered number is a digit" else echo... (2 Replies)
Discussion started by: namishtiwari
2 Replies

3. UNIX for Dummies Questions & Answers

Digits display

Hi there, I am new to scripting. Can anyone help me in writing a script which will display all the digits between 1 and 5 inclusive, one digit per line. Should use a loop to do this. Thanks in advance!! (3 Replies)
Discussion started by: Spoorthi16
3 Replies

4. Shell Programming and Scripting

Formatting digits

I want to check the argument in KSH. If the user type in the prompt 'find 3' it will format 3 to 003 to match the data in the text file. Same as with 10 to 010. Always begins with 0. eg. >find 3 Output: 003 >find 30 Output: 030 (7 Replies)
Discussion started by: harry0013
7 Replies

5. Shell Programming and Scripting

total last digits

hi group, How can I count total number of 5's which are continuous in the end. i.e. in the below string, the o/p should be 4 I just know to calculate total number of 5's $ echo "95952325555" | awk -F "5" '{print NF-1}' 6 (3 Replies)
Discussion started by: uwork72
3 Replies

6. Shell Programming and Scripting

help: single digits inflated to 2 digits

Hi Folks Probably an easy one here but how do I get a sequence to get used as mentioned. For example in the following I want to automatically create files that have a 2 digit number at the end of their names: m@pyhead:~$ for x in $(seq 00 10); do touch file_$x; done m@pyhead:~$ ls file*... (2 Replies)
Discussion started by: amadain
2 Replies

7. Shell Programming and Scripting

Find filenames with three digits and add zeros to make five digits

Hello all! I've looked all over the internet and this site and have come up a loss with an easy way to make a bash script to do what I want to do. I have a file with a naming convention as follows: 2012-01-18 string of words here 123.jpg 2012-01-18 string of words here 1234.jpg 2012-01-18... (2 Replies)
Discussion started by: Buzzman25
2 Replies

8. Shell Programming and Scripting

Showing 4 digits

Hello everybody I'm a little beginer for shell script as I started last night... I have this script cat fichier.txt | while read l ; do #echo $l echo $x x=$(( $x + 1 )) done it's return 1 2 3 4 (4 Replies)
Discussion started by: remibemol
4 Replies

9. UNIX for Beginners Questions & Answers

sed / awk script to delete the two digits from first 3 digits

Hi All , I am having an input file as stated below 5728 U_TOP_LOGIC/U_CM0P/core/u_cortexm0plus/u_top/u_sys/u_core/r03_q_reg_20_/Q 011 611 U_TOP_LOGIC/U_CM0P/core/u_cortexm0plus/u_top/u_sys/u_core/r04_q_reg_20_/Q 011 3486... (4 Replies)
Discussion started by: kshitij
4 Replies
econvert(3C)						   Standard C Library Functions 					      econvert(3C)

NAME
econvert, fconvert, gconvert, seconvert, sfconvert, sgconvert, qeconvert, qfconvert, qgconvert - output conversion SYNOPSIS
#include <floatingpoint.h> char *econvert(double value, int ndigit, int *decpt, int *sign, char *buf); char *fconvert(double value, int ndigit, int *decpt, int *sign, char *buf); char *gconvert(double value, int ndigit, int trailing, char *buf); char *seconvert(single *value, int ndigit, int *decpt, int *sign, char *buf); char *sfconvert(single *value, int ndigit, int *decpt, int *sign, char *buf); char *sgconvert(single *value, int ndigit, int trailing, char *buf); char *qeconvert(quadruple *value, int ndigit, int *decpt, int *sign, char *buf); char *qfconvert(quadruple *value, int ndigit, int *decpt, int *sign char *buf); char *qgconvert(quadruple *value, int ndigit, int trailing, char *buf); DESCRIPTION
The econvert() function converts the value to a null-terminated string of ndigit ASCII digits in buf and returns a pointer to buf. buf should contain at least ndigit+1 characters. The position of the decimal point relative to the beginning of the string is stored indirectly through decpt. Thus buf == "314" and *decpt == 1 corresponds to the numerical value 3.14, while buf == "314" and *decpt == -1 corresponds to the numerical value .0314. If the sign of the result is negative, the word pointed to by sign is nonzero; otherwise it is zero. The least significant digit is rounded. The fconvert() function works much like econvert(), except that the correct digit has been rounded as if for sprintf(%w.nf) output with n=ndigit digits to the right of the decimal point. ndigit can be negative to indicate rounding to the left of the decimal point. The return value is a pointer to buf. buf should contain at least 310+max(0,ndigit) characters to accomodate any double-precision value. The gconvert() function converts the value to a null-terminated ASCII string in buf and returns a pointer to buf. It produces ndigit sig- nificant digits in fixed-decimal format, like sprintf(%w.nf), if possible, and otherwise in floating-decimal format, like sprintf(%w.ne); in either case buf is ready for printing, with sign and exponent. The result corresponds to that obtained by (void) sprintf(buf,``%w.ng'',value) ; If trailing = 0, trailing zeros and a trailing point are suppressed, as in sprintf(%g). If trailing != 0, trailing zeros and a trailing point are retained, as in sprintf(%#g). The seconvert(), sfconvert(), and sgconvert() functions are single-precision versions of these functions, and are more efficient than the corresponding double-precision versions. A pointer rather than the value itself is passed to avoid C's usual conversion of single-precision arguments to double. The qeconvert(), qfconvert(), and qgconvert() functions are quadruple-precision versions of these functions. The qfconvert() function can overflow the decimal_record field ds if value is too large. In that case, buf[0] is set to zero. The ecvt(), fcvt() and gcvt() functions are versions of econvert(), fconvert(), and gconvert(), respectively, that are documented on the ecvt(3C) manual page. They constitute the default implementation of these functions and conform to the X/Open CAE Specification, System Interfaces and Headers, Issue 4, Version 2. USAGE
IEEE Infinities and NaNs are treated similarly by these functions. ``NaN'' is returned for NaN, and ``Inf'' or ``Infinity'' for Infinity. The longer form is produced when ndigit >= 8. ATTRIBUTES
See attributes(5) for descriptions of the following attributes: +-----------------------------+-----------------------------+ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | +-----------------------------+-----------------------------+ |MT-Level |MT-Safe | +-----------------------------+-----------------------------+ SEE ALSO
ecvt(3C),sprintf(3C), attributes(5) SunOS 5.11 3 May 1999 econvert(3C)
All times are GMT -4. The time now is 06:36 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy