所以我是 C 新手,正在自学字符串处理。据我所知,我的问题是我标记 sp 的函数?输入的数字字符串不仅在空格上分裂。例如:如果我输入一个像 45 这样的数字,我的数组中的结果字符串将同时显示 45 和 5,因此无论出于何种原因,它都会在两位数中拆分数字。我已经搜索了很长时间,但没有任何运气。
希望这不是我忽略的明显错误。但是我已经到了无法继续学习的地步,因此不胜感激!
示例输出:
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 . . .
我的代码:
#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" );
}