将文件详细信息读入字符串和int

时间:2017-06-12 14:30:34

标签: c string file io format

我有一个文件,包括(ID-9位,姓名10位,数量-4位),例如:

123456789 Dany Bany 1000
999999999 Bill 9

我想阅读这些细节: ID为字符串,Name为字符串,数字为int。

我该怎么做?我应该考虑有2个单词的名字,其中一些包括1个单词。 我尝试使用它,但有2个单词名称的问题:

while (fscanf(file, "%s %s %d", id, name, &quantity) > 0) {
    printf("%s %s %d\n", id, name, quantity);
}

3 个答案:

答案 0 :(得分:1)

一种方法是使用fgets()函数将整行读入一个字符数组,然后根据需要解析生成的字符串。

在解析结果字符串时,读取第一个空格之前的第一个字符,并将其存储为ID的字符串。然后读取最后一个空格后的字符并转换为int。为此,您必须循环访问char数组,同时使用ctype头文件中的库函数,例如isspace()isdigit()等。

答案 1 :(得分:1)

您可以逐行阅读该文件,并使用split来划分各个部分:

import std.stdio;
import std.array;
import std.conv;

void main() {
    auto f = File("/tmp/file.txt", "r");
    foreach (line ; f.byLine()) {
        auto parts = line.split();
        string id = parts[0].to!string;
        string name = parts[1..$-1].join(' ').to!string;
        int quantity = parts[$-1].to!int;

        writeln("id ", id, " name ", name, " quantity ", quantity);
    }
}

答案 2 :(得分:0)

Read the file line by line, using fgets().

For every line do:

  1. Get the ID, by searching for the first space.
  2. Get the number as a string, by searching for the last space. Convert it to an integer with atoi().
  3. The rest, unprocessed part of the line, is the Name.

Below is a naive and rushed implementation of this logic:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define LEN 100

int main(void)
{
    char line[LEN];
    FILE* fp = fopen("foo.txt", "r");
    while (1) {
        if (fgets(line, 100, fp) == NULL) break;
        printf("%s", line);
        char id[20];
        int j = 0;
        while(line[j] != ' ' && line[j] != '\0')
        {
            id[j] = line[j];
            j++;
        }
        id[j] = '\0';
        //printf("ID: %s\n", id);
        j++;
        size_t len = strlen(line);
        int i, end = 0, k = 0;
        char str_number[20];
        for(i = len - 1; i >= 0; --i)
        {
            if(line[i] == ' ')
            {
                end = i;
                ++i;
                while(i <= len)
                    str_number[k++] = line[i++];
                break;
            }
        }
        //printf("%s\n", str_number);
        int number = atoi(str_number);
        //printf("%d\n", number);
        char name[20];
        k = 0;
        for(i = j; i < end; ++i)
            name[k++] = line[i];
        name[k] = '\0';
        printf("ID: %s\n", id);
        printf("Number: %d\n", number);
        printf("Name: %s\n", name);
    }
    return 0;
}

Output:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
123456789 Dany Bany 1000
ID: 123456789
Number: 1000
Name: Dany Bany
999999999 Bill 9
ID: 999999999
Number: 9
Name: Bill