Alright, I need the code read the user input, tell how many white spaces it skipped over, how many characters there were, and the ending character. HOWEVER, I also need to display an error message if the user enters something other than an integer first:
EX:
56* is okay,
*56 is not okay.
<space><space>4 is okay
.........4 is not okay.
here's my code so far:
Code:
#include <stdio.h>
int
main ()
{
int mainInteger = 0;
printf ("\nEnter an integer: ");
miniScanf ();
printf ("\nMain's integer (printed with a %%d) is now %d \n\n",
mainInteger);
}
int
miniScanf (int mainInteger)
{
int blanks = 0;
int characterCount = 0;
char lastChar;
char error;
char firstChar;
scanf("%c", &mainInteger);
firstChar = mainInteger;
while (mainInteger != '\n')
{
scanf ("%c", &mainInteger);
characterCount++;
while (mainInteger == ' ') //To count the white spaces.
{
scanf ("%c", &mainInteger);
blanks++;
characterCount++;
}
if (firstChar < 48 || firstChar > 57 || firstChar != 32) //ASCII codes for 0-9 and ' '. To produce the error.
{
if (mainInteger == '\n')
{
printf
("\nError, scan terminated by non-whitespace, non-digit before any digits encountered.\n");
printf ("\nSkipped over %d characters of white space.\n\n",
blanks);
printf
("Stopped scanning after %d characters (including the leading whitespace, if any), last character that stopped the scan was a '%c' (0x%x).\n",
characterCount - 1, error, error);
return;
}
}
if (mainInteger == '\n') //To end after user presses enter key.
{
printf ("\nSkipped over %d characters of white space.\n\n", blanks);
printf
("Stopped scanning after %d characters (including the leading whitespace, if any), last character that stopped the scan was a '%c' (0x%x).\n",
characterCount - 1, lastChar, lastChar);
return;
}
else
{
lastChar = mainInteger;
}
}
}
Input/Output:
Enter an integer: 56*
Error, scan terminated by non-whitespace, non-digit before any digits encountered.
Skipped over 0 characters of white space.
Stopped scanning after 2 characters (including the leading whitespace, if any), last character that stopped the scan was a '' (0x0).
Main's integer (printed with a %d) is now 0
Ignoring the obvious problem that the scan was not stopped with a space, but with a *, and that main's integer should now be 56, why is it displaying this error message when the user entered an integer first? I'm not allowed to use string.h or scanf anything other than as a character.
As always, help is most appreciated.