简体   繁体   English

读取C语言中的行并将其转换为浮点数

[英]Reading lines in C and converting to floating point

I have a text file that reads as such: 我有一个文本文件,内容如下:

A 50
B 30
C 40

Currently my code opens this file and reads each line as thus: 当前,我的代码打开此文件并按以下方式读取每一行:

#include <stdio.h>

int main(void)
{
    int file = 0;

    {
        char* filename = "commands.txt";
        FILE* file;
        file = fopen(filename, "a+");
        char line[BUFSIZ];
        while(fgets(line, sizeof(line), file)) {
            char first_letter = line[0];
            printf("%c", first_letter);
            float number = line[2 : end] 
            printf("%f", number)

        }
    }
    return 0;
}

The character variable first_letter is set to the letter. 字符变量first_letter设置为字母。 I have written 2:end but obviously that won't work. 我已经写了2:end,但是显然那行不通。 I would like to set the floating point variable 'number' to whatever the number is on that line. 我想将浮点变量'number'设置为该行上的任何数字。 It may not necessarily be a 2 digit number. 它不一定是2位数字。

Once you read, parse it using sscanf() : 阅读后,使用sscanf()对其进行解析:

  while(fgets(line, sizeof(line), file)) {
        char first_letter;
        float number;
        if( sscanf(line, "%c %f", &first_letter, &number) != 2)
        { /* handle error */ }
        printf("%c %f\n", first_letter, number);

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM