如何在不使用库函数的情况下从文件中将字符串转换为C?

时间:2016-10-10 16:58:30

标签: c

我正在尝试打开一个包含多行数字的文件,然后将其从字符串转换为整数。

我想这样做而不使用任何库函数,所以没有atoi,没有strtol也没有strtoul。

这就是我的代码:

#include <stdio.h>
#include <stdlib.h> /* required for atoi. */
int main(void) {
  int  i, len;
  int result=0;
  double numbers;
  char num[20];  /* declares a char array. */

FILE *file;  /* declare a file pointer. */
file = fopen("test22.txt", "r");  /* opens the text file for reading only, not writing. */

while(fgets(num, 100, file)!=NULL) {       /* this while loop makes it so that it will continue looping until the value is null, which is the very end. */
    len=strlen(num);
    for(i=0; i<len; i++) {
        result = result*10 + ( num[i] - '0' );
    }
    printf("%d\n", result);
    }
fclose(file); /* closes the file */
return 0;
}

现在它正在返回文本文件中不存在的数字。

任何帮助将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:0)

您不会在每个新行重置result为零,因此它会不断累积。变化

while(fgets(num, 100, file)!=NULL) { 
    len=strlen(num);
    for(i=0; i<len; i++) {
        result = result*10 + ( num[i] - '0' );
    }
    printf("%d\n", result);
    }

while(fgets(num, 100, file)!=NULL) {
    result = 0;
    len=strlen(num);
    // account for newline - should really be smarter than this.
    // I'll leave that as an exercise for the reader... ;)
    for(i=0; i< (len - 1); i++) {
        result = result*10 + ( num[i] - '0' );
    }
    printf("%d\n", result);
    }

答案 1 :(得分:0)

函数fgetsnewline保留在字符串末尾(如果存在),您尝试将其转换为数字。我建议像这样的循环:

for(i=0; i<len && isdigit(num[i]); i++)

你还必须

result = 0;
for(i=0; i<len && isdigit(num[i]); i++)
在每个循环之前

请注意,您不能只减少strlen的结果,因为文件的最后一行可能没有newline

编辑:由于您发布了一个带负数的文件,以下是一个将转换它们的示例。

#include <stdio.h>
#include <ctype.h>

int getnum(char *str) 
{
    int result  = 0;
    int neg = 0;
    if(*str == '-') {
        neg = 1;
        str++;
    }
    while(isdigit(*str)) {
        result = result * 10 + *str - '0';
        str++;
    }
    if(neg) {
        return -result;
    }
    return result;

}

int main(void)
{
    printf("%d\n", getnum("123456789\n"));
    printf("%d\n", getnum("-987654321\n"));
    return 0;
}

节目输出:

123456789
-987654321