读取整数不分割

时间:2014-04-23 11:08:07

标签: c file

大家好,如何从文件中读取整个数字?我的意思是我的输入文件是100-4 / 2,我写了这段代码while(fscanf(in,"%s",s)!=EOF),但它读起来像这样的1 0 0.我想读100像。如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

这可能是因为在使用双字节字符(Unicode)写入文件时使用的是单字节字符(ANSI)集。如果您使用读取它的相同程序创建了该文件,它将正确读取它,但如果没有,您可以在记事本中打开您正在读取的文件,然后单击另存为,然后您可以选择ANSI或Unicode。

答案 1 :(得分:0)

你可以使用getline()或类似的方法一次读取整行(如果只有一行,你也可以读到,当EOF为真时,读取整行)。然后,您可以解析该行以提取数字和运算符。

答案 2 :(得分:0)

"%d"用于整数

int value;
if (scanf("%d", &value) != 1) /* error */;
printf("Value read is %d.\n", value);

答案 3 :(得分:0)

以下简单程序是自解释的,它逐个字符地读取文件,每次迭代都将该字符存储到临时变量temp中。当temp中的值是数字字符时,它只是将此值复制到名为s的数组中。

int main()
{
 char s[10]="\0";//initialzing array to NULL's and assuming array size to be 10
 int i=0,temp=0;
 FILE *fp=fopen("t.txt","r"); //when file has 100-4/2 
     if(fp==NULL)
     {
        printf("\nError opening file.");
        return 1;
     }
     while( (temp=fgetc(fp))!=EOF && i<10 ) //i<10 to not exceed array size.. 
     {
        if(temp>='0' && temp<='9')//if value in temp is a number (simple logic...)
        {
            s[i]=temp;
            i++;
        }   
     }
     printf("%s",s);//outputs 10042
return 0;
}
相关问题