Unable to extract full number from string in C program - c

Program to calculate the average of n numbers given by the user.
Okay so I have this program whose purpose is what you have read above. Its output is not quite right. I figured out what the problem is but couldn't find the solution as I am not a leet at programming (newbie actually). Here is the code:
#include <stdio.h>
int main(void) {
char user_data[100];
long int sum = 0;
double average;
unsigned int numbers_count = 0;
for (int i = 0; i <= 99; ++i)
user_data[i] = 0;
unsigned int numbers[100];
for (int i = 0; i <= 99; ++i)
numbers[i] = 0;
printf("Please enter the numbers:");
fgets(user_data, sizeof(user_data), stdin);
int i = 0;
while (user_data[i] != 0) {
sscanf(user_data, "%u", &numbers[i]);
++i;
}
i = 0;
while (numbers[i] != 0) {
sum += numbers[i];
++i;
}
i = 0;
while (numbers[i] != 0) {
++numbers_count;
++i;
}
average = (float)sum / (float)numbers_count;
printf("\n\nAverage of the entered numbers is: %f",average);
return 0;
}
Now here comes the problem.
When I enter an integer say 23, it gets stored into the user_data in two separate bytes. I added a loop to print the values of user_data[i] to figure out what was wrong.
i = 0;
while (i <= 99) {
printf("%c\n",user_data[i]);
++i;
}`
and the result was this
user_data insight
This was the first problem, here comes the second one.
I added another loop same like the above one to print the numbers stored in numbers[100] and figure out what was wrong and here is the output. Here's a sample
numbers stored in numbers[]
Now my main question is
How to extract the full number from user_data?

I believe it could be helpful to layout user_data after the fgets() of "23" (assuming Linux or Mac new line):
+-----+-----+----+----+
| '2' | '3' | \n | \0 | .....
+-----+-----+----+----+
0 1 2 3
Note that user_data[0] does not contain 2 (the number 2)! It contains '2' (the character '2') whose code is (again, assuming Linux) 0x32 (in hex or 50 in decimal).
This is why your attempt to print the values of user_data[] have not been fruitful: you were trying to print the representation of the number, not the number itself.
To convert that string to the integer it represents, you can do something like:
num = atoi(user_data)
The function atoi() does the work for you. A more flexible function is strtol() which does the same but for long int (and also can handle string that represents numbers in a base that is not 10).
I hope this answers to your question: How to extract the full number from user_data?
There are some other points where you should clean up and simplify your code, but you can open another question in case you need help.

Try this:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int i;
char user_data[100];
long int sum = 0;
double average;
unsigned int numbers_count = 0;
for( i=0; i<= 99; ++i)
user_data[i] = 0;
unsigned int numbers[100];
for( i=0; i<= 99; ++i)
numbers[i] = 0;
printf("Please enter the numbers:");
fgets(user_data,sizeof(user_data),stdin);
//int p=0;//use with strtol(see further code)
i = 0;
int j;//this will store each number in numbers array.. so this is also the count of numbers stored - 1
for(j=0;;){
for(i=0;i<strlen(user_data);i++)
{
if(user_data[i]=='\n'){
break;
}
if(user_data[i]==' '){
j++;
i++;
//p=i;//to be used with strtol
}
numbers[j]=(numbers[j]*10)+((user_data[i]-48));//alternatively use => numbers[j]=strtol(user_data+p,NULL,10);
}
break;
}
i = 0;
while( i<=j)
{
sum += numbers[i];
++i;
}
average = (float)sum/(j+1);
printf("\n\nAverage of the entered numbers is: %f",average);
return 0;
}
Sample input
10 11 12
Sample output
11.00000000
I have shown two approaches to solve this:
One is straight-forward, subtract 48 from each char and add it to numbers array(ASCII manipulation) .
Other is to use strtol. Now strtol converts the number pointed by the char pointer(char array in this case) until the next char is not a number. So use pointer arithmetic to point to further numbers(like here I have added p(yeah I know p is not a good variable name, so does i and j!)).
There are more ways to solve like using atoi library functions.

regarding the posted code:
what happens if one of the numbers is zero?
What happens if the sum of the numbers exceeds the capacity of 'sum'
#include <stdio.h> // sscanf(), fgets(), printf()
#include <stdlib.h> // strtol()
#include <string.h> // strtok()
// eliminate the 'magic' number by giving it a meaningful name
#define MAX_INPUTS 100
int main(void)
{
// the array can be initialized upon declaration
// which eliminates the 'for()' loop to initialize it
// char user_data[100];
// and
// initialization not actually needed as
// the call to 'fgets()' will overlay the array
// and 'fgets()' always appends a NUL byte '\0'
char user_data[ MAX_INPUTS ];
long int sum = 0;
double average;
// following variable not needed
// unsigned int numbers_count = 0;
// following code block not needed when
// 'user_data[]' initialized at declaration
// for (int i = 0; i <= 99; ++i)
// user_data[i] = 0;
// not needed, see other comments
//unsigned int numbers[100];
// not needed, as 'numbers' is eliminated
// for (int i = 0; i <= 99; ++i)
// numbers[i] = 0;
printf("Please enter the numbers:");
// should be checking the returned value
// to assure it is not NULL
// And
// this call to 'fgets()' is expecting
// all the numbers to be on a single input line
// so that could be a problem
fgets(user_data, sizeof(user_data), stdin);
// the following two code blocks will not extract the numbers
// for a number of reasons including that 'sscanf()'
// does not advance through the 'user_data[]' array
// int i = 0;
// while (user_data[i] != 0) {
// sscanf(user_data, "%u", &numbers[i]);
// ++i;
// }
// i = 0;
// while (numbers[i] != 0) {
// sum += numbers[i];
// ++i;
// }
// suggest the following,
// which also eliminates the need for 'numbers[]'
// note: the literal " \n" has both a space and a newline
// because the user is expected to enter numbers,
// separated by a space and
// 'fgets()' also inputs the newline
int i = 0;
char *token = strtok( user_data, " \n");
while( token )
{
// not everyone likes 'atoi()'
// mostly because there is no indication of any error event
// suggest using: 'strtol()'
//sum += atoi( token );
sum += strtol( token, NULL, 10 ) // could add error checking
i++;
token = strtok( NULL, " \n" );
}
// the value assigned to 'numbers_count'
// is already available in 'i'
// suggest eliminate the following code block
// and
// eliminate the 'numbers_count' variable
// i = 0;
// while (numbers[i] != 0) {
// ++numbers_count;
// ++i;
// }
// 'average' is declared as a 'double',
// so the casting should be to 'double'
// and
// if incorporating the prior comment about 'numbers_count'
// average = (float)sum / (float)numbers_count;
average = (double)sum / (double)i'
// to have the text immediately displayed on the terminal
// place a '\n' at the end of the format string.
// without adding the '\n' the text only displays
// as the program exits
// printf("\n\nAverage of the entered numbers is: %f",average);
printf("\n\nAverage of the entered numbers is: %f\n",average);
return 0;
} // end function: main

Related

Different algorithm for reversing a number using expanded form of numbers

Below is the code for reversing a number (in the standard way)
#include <stdio.h>
int main()
{
int result=0;
int q,n,rem;
printf("enter number: ");
scanf("%d",&n);
q=n;
while(q!=0){
rem=q%10;
result=result*10+rem;
q=q/10;
}
printf("reversed number is: %d",result);
return 0;
}
But I was thinking whether there is a way to find the reversed program using the expanded form of numbers?
For example: If the input to the program is 123, then the required output would be 321 which can be written as 3 * 100+2 * 10+1 * 1
I'm not quite sure what you mean by a "different algorithm for reversing a number using expanded form of numbers."
Perhaps this is a solution to what you are asking:
Take each digit, one at a time, moving from right to left across the number and multiply that digit by the multiple of 10 associated with the current left-most digit. Accumulate these values in the variable reverse.
e.g. number = 123, digitCount = 3, power = 100, reverse = 0
for loop executed digitCount times (3 times)
get current right-most digit (3)
multiply current right-most digit (3) times current left-most multiple of 10 (100) = 300
reverse = 300
drop right-most digit from number (number changes from 123 to 12)
adjust multiple of 10 (power changes from 100 to 10)
continue with second pass through loop, etc.
Also your version of the program will not properly handle trailing zeroes. The printf statement at the end of this program will fill in any formerly trailing zeroes which now should be leading zeroes.
/* reverse.c
reverse the digits of a non-negative integer and display it on the terminal
uses an advanced formatting option of printf() to handle any trailing zeroes
e.g. 500 produces 005
*/
#include <stdio.h>
int main (void)
{
printf("\n"
"program to reverse a number\n"
"\n"
"enter a number: ");
int number;
scanf ("%d", &number);
printf("\n");
int digitCount = 1;
int power = 1;
while (number / power > 9) {
++digitCount;
power *= 10;
}
// power = multiple of 10 matching left-most digit in number
// e.g. if number = 123 then power = 100
int reverse = 0;
for (int i = 1; i <= digitCount; ++i) {
reverse += number % 10 * power; // number % 10 = right-most digit
number /= 10; // drop right-most digit
power /= 10; // adjust multiple of 10
}
// .* represents a variable that specifies the field width (the minimum number of
// digits to display for an integer and with unused digits filled by leading zeroes)
printf("reversed number: %.*d\n", digitCount, reverse);
return 0;
}
There is no particular logic like that,if you are interested to acheive that kind of output, you can just come up with something like this
#include <stdio.h>
#include <math.h>
int main()
{
int result=0;
int q,n,rem;
printf("enter number: ");
scanf("%d",&n);
q=n;
int number[100];
for (int i = 0; i < 100 ; i++){
number[i] = -1;
}
int i=0;
while(q!=0){
rem=q%10;
number[i++]= rem;
q=q/10;
}
int size=0;
for (i = 0; i < 100 ; i++){
if(number[i]== -1) break;
else{
size++;
}
}
int tenPowers= size;
for(int i=0; i<=size-1 && tenPowers>=0 ;i++){
printf("%dx%d", number[i],(int)pow(10,tenPowers-1));
tenPowers=tenPowers-1;
if(tenPowers>=0) printf("+");
}
return 0;
}
You can have this. It's not reversing, but it's formatting the output for you. Reversing a binary number or a string is not difficult.
int main() {
int n = 123456;
char in[16], obuf[] = " + x*10000000";
sprintf( in, "%d", n );
int rev = strlen( in ) + 2;
for( int o=3, i=0; (obuf[3] = in[i]) != '\0'; o=0, i++ )
printf( "%.*s", rev+3-o-i-(in[i+1]?0:2), obuf+o );
return 0;
}
Output
1*100000 + 2*10000 + 3*1000 + 4*100 + 5*10 + 6
You can expand the sizes to suit your needs.

Digit Frequency calculating code in C not working

So, I was writing this code for counting the digit frequency i.e. the number of times the digits from 0-9 has appeared in a user inputted string(alphanumeric). So, I took the string, converted into integer and tried to store the frequency in "count" and print it but when I run the code, count is never getting incremented and the output comes all 0s. Would be grateful if anyone points out in which part my logic went wrong.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
// takes string input
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
//turns the string to int
int x = atoi(s);
int temp = x, len = 0;
//calculates string length
while (x != 0) {
x = x / 10;
len++;
}
x = temp;
//parses through the string and matches digits with each number
for (int j = 0; j < 10; j++){
int count = 0;
for(int i = 0; i < len; i++){
if(x % 10 == j){
count++;
}
x = x / 10;
}
x = temp;
printf("%d ", count);
}
return 0;
}
To write a correct and reasonable digit-counting program:
Do not allocate any buffer for this.
Create an array to count the number of times each digit occurs. The array should have ten elements, one for each digit.
Initialize the array to zero in each element.
In a loop, read one character at a time.
Leave the loop when the read routine (such as getchar) indicates end-of-file or a problem, or, if desired, returns a new-line or other character you wish to use as an end-of-input indication.
Inside the loop, check whether the character read is a digit. If the character read is a digit, increment the corresponding element of the array.
After the loop, execute a new loop to iterate through the digits.
Inside that loop, for each digit, print the count from the array element for that digit.
Your approach is way to complicated for a very easy task. This will do:
void numberOfDigits(const char *s, int hist[10]) {
while(*s) {
if(isdigit(*s))
hist[*s - '0']++;
s++;
}
}
It can be used like this:
int main(void) {
char buf[1024];
int hist[10];
fgets(buf, sizeof buf, stdin);
numberOfDigits(s, hist);
for(int i=0; i<10; i++)
printf("Digit %d occurs %d times\n", i, hist[i]);
}
This can also be quite easily achieved without a buffer if desired:
int ch;
int hist[10];
while((ch = getchar()) != EOF) {
if(isdigit(ch))
hist[ch - '0']++;
}
#include <stdio.h>
int main(void) {
int input = 1223330;
int freq[10] = {0};
input = abs(input);
while(input)
{
freq[input%10]++;
input /= 10;
}
for(int i=0; i<10; ++i)
{
printf("%d: %.*s\n", i, freq[i], "*************************************************");
}
return 0;
}
Output:
Success #stdin #stdout 0s 5668KB
0: *
1: *
2: **
3: ***
4:
5:
6:
7:
8:
9:
This app is currently limited by the size of an int (approximately 9 or 10 digits).
You can update it to use a long long easily, which will get you to about 19 digits.

calculate sum of all numbers present in the string

I am solving this problem:
Given a string str containing alphanumeric characters, calculate sum
of all numbers present in the string.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test
cases follow. Each test case contains a string containing alphanumeric characters.
Output:
Print the sum of all numbers present in the string.
Constraints:
1 <= T<= 105
1 <= length of the string <= 105
Example:
Input:
4
1abc23
geeks4geeks
1abc2x30yz67
123abc
Output:
24
4
100
123
I have come up with the following solution:
#include <stdio.h>
#include <string.h>
int main() {
//code
int t,j;
char a[100000];
scanf("%d",&t);
while(t--)
{
int sum=0,rev=0,i=0,l;
scanf("%s",a);
l=strlen(a);
for(i=0;i<l;i++)
{
if (isdigit(a[i])){
while(isdigit(a[i])){
rev = rev *10 + (a[i]-48);
i++;
}
}
sum+=rev;
rev=0;
}
printf("%d\n",sum);
}
return 0;
}
This code is working fine.
BUT if loop termination condition is changed from i < l to a[i]!='\0', then code doesn't work. Why?
I would loop backwards over the string. No nested loops. Just take the 10s exponent as you move left
You have the length of the string, so there should be no reason to check for NUL char yourself
(untested code, but shows the general idea)
#include <math.h>
l=strlen(a);
int exp;
exp = 0;
for(i = l-1; i >= 0; i--)
{
if (isdigit(a[i])) {
rev = a[i]-48; // there are better ways to parse characters to int
rev = (int) pow(10, exp) * rev;
sum += rev; // only add when you see a digit
} else { exp = -1; } // reset back to 10^0 = 1 on next loop
exp++;
}
Other solutions include using regex to split the string on all non digit characters, then loop and sum all numbers
You will have to change the logic in your while loop as well if you wish to change that in your for loop condition because it's quite possible number exists at the end of the string as well, like in one of your inputs 1abc2x30yz67. So, correct code would look like:
Snippet:
for(i=0;a[i]!='\0';i++)
{
if (isdigit(a[i])){
while(a[i]!='\0' && isdigit(a[i])){ // this line needs check as well
rev = rev *10 + (a[i]-48);
i++;
}
}
sum+=rev;
rev=0;
}
On further inspection, you need the condition of i < l anyways in your while loop condition as well.
while(i < l && isdigit(a[i])){
Update #1:
To be more precise, the loop while(isdigit(a[i])){ keeps going till the end of the string. Although it does not cause issues in the loop itself because \0 ain't a digit, but a[i] != '\0' in the for loop condition let's you access something beyond the bounds of length of the string because we move ahead 1 more location because of i++ in the for loop whereas we already reached end of the string inside the inner while loop.
Update #2:
You need an additional check of a[i] == '\0' to decrement i as well.
#include <stdio.h>
#include <string.h>
int main() {
//code
int t,j;
char a[100000];
scanf("%d",&t);
while(t--)
{
int sum=0,rev=0,i=0,l;
scanf("%s",a);
l=strlen(a);
for(i=0;a[i]!='\0';i++)
{
if (isdigit(a[i])){
while(a[i] != '\0' && isdigit(a[i])){ // this line needs check as well
rev = rev *10 + (a[i]-48);
i++;
}
}
if(a[i] == '\0') i--; // to correctly map the last index in the for loop condition
sum+=rev;
rev=0;
}
printf("%d\n",sum);
}
return 0;
}
Update #3:
You can completely avoid the while loop as well as shown below:
#include <stdio.h>
#include <string.h>
int main() {
//code
int t,j;
char a[100005];
scanf("%d",&t);
while(t--)
{
int sum=0,rev=0,i=0,l;
scanf("%s",a);
l=strlen(a);
for(i=0;i<l;i++) {
if (isdigit(a[i])){
rev = rev * 10 + (a[i]-48);
}else{
sum += rev;
rev = 0;
}
}
printf("%d\n",sum + rev); // to also add last rev we captured
}
return 0;
}
Other answers have pointed out the correct loop conditions to ensure proper operation of your program.
If you are allowed to use library functions other than isdigit, I would recommend using strtol with the EndPtr parameter (output parameter that points to the character in the string that caused strtol to stop scanning a number):
char str[] = "1abc23def5678ikl";
int main()
{
char *pStop = str;
int n, accum = 0;
size_t len = strlen(str);
do
{
n = strtol(pStop, &pStop, 10);
pStop++;
if(n)
{
printf("%d\n", n);
accum += n;
}
}
while(pStop < &str[len]);
printf("Total read: %d\n", accum);
return 0;
}

Manipulating dynamically allocated 2D char arrays in C

I'm having trouble with trying to manipulate 2d dynamic arrays in C. What I want to do is to store a char string in every row of the the 2d array then perform a check to see if the string contains a certain character, if so remove all occurrences then shift over the empty positions. What's actually happening is I get an exit status 1.
More about the problem, for example if I have
Enter string 1: testing
Enter string 2: apple
Enter string 3: banana
I would want the output to become
What letter? a // ask what character to search for and remove all occurences
testing
pple
bnn
Here is my full code:
#include <stdio.h>
#include <stdlib.h>
void removeOccurences2(char** letters, int strs, int size, char letter){
// Get size of array
// Shift amount says how many of the letter that we have removed so far.
int shiftAmt = 0;
// Shift array says how much we should shift each element at the end
int shiftArray[strs][size];
// The first loop to remove letters and put things the shift amount in the array
int i,j;
for(i=0;i < strs; i++){
for(j = 0; j < size - 1; j++) {
if (letters[i][j] == '\0'){
break;
}
else {
// If the letter matches
if(letter == letters[i][j]){
// Set to null terminator
letters[i][j] = '\0';
// Increase Shift amount
shiftAmt++;
// Set shift amount for this position to be 0
shiftArray[i][j] = 0;
}else{
// Set the shift amount for this letter to be equal to the current shift amount
shiftArray[i][j] = shiftAmt;
}
}
}
}
// Loop back through and shift each index the required amount
for(i = 0; i < strs; i++){
for(j = 0; j < size - 1; j++) {
// If the shift amount for this index is 0 don't do anything
if(shiftArray[i][j] == 0) continue;
// Otherwise swap
letters[i][j - shiftArray[i][j]] = letters[i][j];
letters[i][j] = '\0';
}
//now print the new string
printf("%s", letters[i]);
}
return;
}
int main() {
int strs;
char** array2;
int size;
int cnt;
int c;
char letter;
printf("How many strings do you want to enter?\n");
scanf("%d", &strs);
printf("What is the max size of the strings?\n");
scanf("%d", &size);
array2 = malloc(sizeof(char*)*strs);
cnt = 0;
while (cnt < strs) {
c = 0;
printf("Enter string %d:\n", cnt + 1);
array2[cnt] = malloc(sizeof(char)*size);
scanf("%s", array2[cnt]);
cnt += 1;
}
printf("What letter?\n");
scanf(" %c", &letter);
removeOccurences2(array2,strs,size,letter);
}
Thanks in advance!
You can remove letters from a string in place, because you can only shorten the string.
The code could simply be:
void removeOccurences2(char** letters, int strs, int size, char letter){
int i,j,k;
// loop over the array of strings
for(i=0;i < strs; i++){
// loop per string
for(j = 0, k=0; j < size; j++) {
// stop on the first null character
if (letters[i][j] == '\0'){
letters[i][k] = 0;
break;
}
// If the letter does not match, keep the letter
if(letter != letters[i][j]){
letters[i][k++] = letters[i][j];
}
}
//now print the new string
printf("%s\n", letters[i]);
}
return;
}
But you should free all the allocated arrays before returning to environment, and explicitely return 0 at the end of main.
Well, there are several issues on your program, basically you are getting segmentation fault error because you are accessing invalid memory which isn't allocated by your program. Here are some issues I found:
shiftAmt isn't reset after processing/checking each string which lead to incorrect value of shiftArray.
Values of shiftArray only set as expected for length of string but after that (values from from length of each string to size) are random numbers.
The logic to delete occurrence character is incorrect - you need to shift the whole string after the occurrence character to the left not just manipulating a single character like what you are doing.
1 & 2 cause the segmentation fault error (crash the program) because it causes this line letters[i][j - shiftArray[i][j]] = letters[i][j]; access to unexpected memory. You can take a look at my edited version of your removeOccurences2 method for reference:
int removeOccurences2(char* string, char letter) {
if(!string) return -1;
int i = 0;
while (*(string+i) != '\0') {
if (*(string+i) == letter) {
memmove(string + i, string + i + 1, strlen(string + i + 1));
string[strlen(string) - 1] = '\0'; // delete last character
}
i++;
}
return 0;
}
It's just an example and there is still some flaw in its logics waiting for you to complete. Hint: try the case: "bananaaaa123"
Happy coding!
"...if the string contains a certain character, if so remove all occurrences then shift over the empty positions."
The original string can be edited in place by incrementing two pointers initially containing the same content. The following illustrates.:
void remove_all_chars(char* str, char c)
{
char *pr = str://pointer read
char *pw = str;//pointer write
while(*pr)
{
*pw = *pr++;
pw += (*pw != c);//increment pw only if current position == c
}
*pw = '\0';//terminate to mark last position of modified string
}
This is the cleanest, simplest form I have seen for doing this task. Credit goes to this answer.

Check to see if scanf is not a float

#define maximum 100
#include <math.h>
#include <stdio.h>
int main () {
float sum, mean, variance, difference;
float sumforvariance, standarddev;
sumforvariance=0;
sum=0;
mean=0;
variance=0;
difference=0;
standarddev=0;
int a, count, b, c;
float insertnum[maximum]
for (a=0; a<maximum; a++) {
scanf("%f",&insertnum[a]);
count ++;
if (insertnum[a]==35.00) {
if (count==1) {
printf ("no data\n");
return 0;
}
break;
}
}
for (b=0; b<count; b++) {
sum+=insertnum[b];
}
mean=sum/count;
for (c=0; c<count; c++) {
difference=insertnum[c]-mean;
sumforvariance=sumforvariance+pow(difference,2);
}
variance=variance/count;
standarddev=sqrt(variance);
printf("mean: %f",mean);
printf("standdev: %f",standarddev);
Hi so I have a simple question. I am trying to calculate a standard deviation and mean for a set of numbers like this
./a.out 12 20 30 etc #
The # is to terminate inputing more numbers. As you can see in the first for loop, I am trying to input the numbers from standard output into an array of floats. The problem is when I enter 35, I do not want to terminate inputting more numbers because its not equal to #. How am I able to enter 35 and continue to enter more numbers until I enter # since they both contain the same numerical value. #=35 and 35=35.
Read you user input in as a string. Sniff for the terminating condition, then convert from string to float. Using the helper function, strtof which is available from #include <stdlib.h>
#define maximum 100
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
float sum, mean, variance, difference;
float sumforvariance, standarddev;
sumforvariance = 0;
sum = 0;
mean = 0;
variance = 0;
difference = 0;
standarddev = 0;
int a, count=0, b, c;
float insertnum[maximum];
for (a = 0; a < maximum; a++) {
char userinput[101] = {0};
userinput[0] = '\0';
scanf("%100s", userinput);
if (userinput[0] == '#')
{
break;
}
insertnum[count] = strtof(userinput, nullptr);
count++;
}
return 0;
}
Also, you forgot to initialize count. And your code was inserting the # read into the array as well. So I fixed that for you.
Aside - I'll never forget the day my computer science professor passionately screamed to the class about the dangers of "reading numbers" from input. Users type characters with the keyboard not numbers. Hence, "validating input" became engrained with me to this day. You might want to consider just letting your loop break whenever the user types anything not a number. A modified version of the loop as follows:
for (a = 0; a < maximum; a++) {
char userinput[101] = {0};
userinput[0] = '\0';
scanf("%100s", userinput);
char* endptr = NULL;
float f = strtof(userinput, &endptr);
if (userinput == endptr)
{
// whatever was typed was not a float
break;
}
insertnum[count] = f;
count++;
}
Check the return value of scanf -- when it successfully converts a float it will return 1 (or more generally, however many conversions in the format string succeeded). So when the input is #, it will return 0 (nothing converted) and leave the # on in the input stream. You can then check the next character to make sure its a #. So you end up with a loop like:
for (a=0; a<maximum && scanf("%f",&insertnum[a]) == 1; a++) {
++count;
}
or even
for (count=0; count < maximum && scanf("%f",&insertnum[count]) == 1; ++count);
if (count == maximum) {
// read the limit -- may be more data
} else {
if (getchar() == '#') {
// got the expected terminator
} else {
// something else caused a problem

Resources