Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with string error checking

Status
Not open for further replies.

darr01

Programmer
Oct 24, 2001
28
MY
Hi, all. I'm having some problems with error checking for strings that has more than one word (i.e. sentences or phrases).

Say for example, I need the user to input a book title into an array (e.g. booktitle[40]).
I also need to do some error checking to see if the booktitle input is more than the allowed number of characters inside the array (i.e. booktitle[40]). If it is more than 39 characters, I need to notify the user than they have entered more than the number of characters allowed.

If I used scanf for input, the counting of characters would be straight forward but only the first word can be counted. Therefore, I tried to use gets or fgets, which would be able to store the whole booktitle but I am at a lost in trying to figure out how to do the above error checking.

Is there a way around it?

Thanks and regards,

Darryl HB
 
I saw an example that used a regexp terminated with
a newline to delimit a buffer. I am a C newbie so
I don't know if this would work, but from working with
awk and tcl,it would work fine there.
 
#include <stdio.h>

#define MAX_TITLE 10

void Clear_Buffer();

int main() {

char sBookTitle[MAX_TITLE+1]; //(11) The last element is
// to hold '\0'.
char cGetChar;
int iCharCount;
int iErrorFlag;
int iOK;

printf( &quot;Enter the book title (10 char max): &quot; );

iCharCount = 0;
iErrorFlag = 0;
iOK = 0;

while ( !iOK )
{

while ( 1 )
{

cGetChar = getchar();

if ( cGetChar == '\n' )
break;
else
sBookTitle[iCharCount] = cGetChar;


if ( iCharCount == MAX_TITLE )
{
iErrorFlag = 1;
break;
}
else
++iCharCount;

}



if ( iErrorFlag )
{
printf( &quot;Too many char's. Try again: &quot; );
iOK = 0;
iCharCount = 0;
iErrorFlag = 0;
Clear_Buffer();

}
else
{

sBookTitle[iCharCount] = '\0';
printf( &quot;Your string: %s\n&quot;,sBookTitle );
iOK = 1;

}



}


return 0;

}

void Clear_Buffer() {

char cBuffer;

cBuffer = 0;

while ( cBuffer != '\n' )
scanf( &quot;%c&quot;,&cBuffer );

}

Mike L.G.
mlg400@blazemail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top