So I'm new to C and am teaching myself string handling. My issue so far as I can tell is that my function that tokenizes sp? the input string of numbers is not only cleaving on the spaces. For instance: if I input a number like 45, the resultant string in my array would show both 45 and the 5, so in two digit numbers it is splitting the number for whatever reason. I've searched at length but have not had any luck.
Hopefully it's not a glaring error that I'm just overlooking. But I've reached the point where I can't continue with my learning so any help is appreciated!
Example output:
please enter your string: 1 45 30 82
converting strings to ints
Printing the string
1, 0, 45, 5, 0, 30, 0, 0, 82, 2,
Press any key to continue . . .
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#define STRING_LENGTH 81
#define MAX_TOKENS 40
int StrInput( char dataStr[]);
void atoiWorker( char dataStr[], char results[], int idx);
void printer ( char dataStr[], int idx);
void tokenize ( char dataStr[], char results[]);
int main()
{
int idx;
char dataStr[STRING_LENGTH];
char results[STRING_LENGTH];
idx = StrInput(dataStr);
tokenize(dataStr, results);
atoiWorker(dataStr, results, idx);
printer(results, idx);
}
int StrInput(char dataStr[])
{
int idx = 0;
printf( "please enter your string: " );
while (idx < (STRING_LENGTH) && ((dataStr[idx] = getchar()) != '\n'))
idx++;
dataStr[idx] = '\0';
return idx;
}
void atoiWorker( char dataStr[], char results[], int idx)
{
int i;
printf( "converting strings to ints\n" );
for (i = 0; i < idx; i++)
results[i] = atoi(&dataStr[i]);
}
void tokenize(char dataStr[], char *results[])
{
int count = 0;
char delim[] = " ,\t\n"; //found this on msdn, hopefully it's right
if (results[0] = strtok(dataStr, " \t"))
count++;
while (results[count] = strtok(NULL, delim/*" \t"*/))
count++;
}
void printer(char dataStr[], int idx)
{
int i;
printf( "Printing the string\n" );
for (i = 0; i < idx; i++)
printf( " %d,", dataStr[i] );
printf( "\n" );
}
results
? You are assigning integers, char pointers, and chars to it's elements at different locations.tokenize
don't match.