2013-03-15 57 views
-1

假设我想在阅读和数字4在C时的读数混合字符和文字数字从文件

5000  49  3.14  Z  100 
0322  35  9.21  X  60 

乘1号目前我有,但我只能够复制信息不操纵信息

#include <stdio.h> 
#include <stdlib.h> 
#define FILE_1 "File1.txt" 
#define FILE_2 "File2.txt" 
int main (void) 
{ 
    // Local Declarations 
    char score; 
    int curCh; 
    int count = 0; 
    FILE* sp1; 
    FILE* sp2; 

    if (!(sp1 = fopen (FILE_1, "r"))) //check if file is there 
    { 
     printf ("\nError opening %s.\n", FILE_1); 
     return (1); 
    } // if open error 
    if (!(sp2 = fopen (FILE_2, "w"))) 
    { 
     printf ("\nError opening %s.\n", FILE_2); 
     return (2); 
    } // if open error 

    while((curCh = fgetc(sp1)) != EOF) 
    { 
     printf ("%c", curCh); //copy the contents 
      count++; 
    } // while 


    return 0; 
} 
+1

您标记fcsnf,但不要在您的代码中使用它。也就是说,你可能会发现fgets()和sscanf()提供了一种更简洁的方式来解析这种类型的数据。 – 2013-03-15 01:26:15

+0

@RandyHoward也许,如果该文件是标准输入。当文件是另一个文件时,fscanf通常不是问题,因为输入不是很不规则。 – Sebivor 2013-03-15 02:10:37

+0

你的问题在哪里? – Sebivor 2013-03-15 02:11:19

回答

0

将1乘以4很容易:1 * 4

你的意思是“乘以better_identifierbest_identifier,uint64_t值从同一个文件读取”?什么是你能想出的最好的标识符?

你需要这些#include S:

#include <stdio.h> 
#include <assert.h> 
#include <stdint.h> 
#include <inttypes.h> 

不要忘记评论了这一点:

/*while((curCh = fgetc(sp1)) != EOF) 
{ 
    printf ("%c", curCh); //copy the contents 
     count++; 
}*/ // Make sure you comment this, because the side-effect of this 
    // ... won't allow you to do anything else with sp1, until you 
    // ... rewind 

哪一本书是你的方式阅读,?

uint64_t better_identifier = 0, best_identifier = 0; 
assert(fscanf(sp1, "%"SCNu64" %*d %*g %*c %"SCNu64, &better_identifier, &best_identifier) == 2); 
printf("%"PRIu64" * %"PRIu64" = %"PRIu64"\n", better_identifier, best_identifier, better_identifier * best_identifier); 

也许你想用xy作为标识符。当然你可以拿出比这更好的标识符!

uint64_t x = 0, y = 0; 
assert(fscanf(sp2, "%"SCNu64" %*d %*g %*c %"SCNu64, &x, &y) == 2); 
printf("%"PRIu64" * %"PRIu64" = %"PRIu64"\n", x, y, x * y); 
1

同意兰迪和乔纳森的意见,你应该使用fgets()来处理整行。如果您已经知道分隔符(如制表符)和已知列,则可以使用strtok()在分隔符上标记行,然后使用计数来提取所需的值。

除的sscanf(),您也许能够 用的atoi()和ATOF() 使成功使用与strtol(的)脱身如下兰迪的评论指出,和其他地方引用StackOverflow的:

+0

我在一小时前的评论中提到过使用fgets()/ sscanf(),但从那时起他已经多次修改了他的问题,但是仍然没有尝试自己解析数据。他似乎想要为他做这件事。 atoi()和atof()都被弃用了。看看strtol()/ strtod()等。 – 2013-03-15 02:32:50

+0

@RandyHoward对不起,我错过了你的第一条评论;编辑我的帖子,以反映您的输入re:atoi/atof。 – SeKa 2013-03-15 08:31:09

相关问题