从文本文件中读取字符串和整数

2024-04-13

假设我有一个如下所示的文件

51.41 52.07 52.01 51.22 50.44 49.97 Coal Diggers
77.26 78.33 78.29 78.12 77.09 75.74 Airplane Flyers
31.25 31.44 31.43 31.09 31.01 30.92 Oil Fracting and Pumping
52.03 12.02 12.04 22.00 31.98 61.97 Big Bank
44.21 44.32 44.29 43.98 43.82 43.71 Rail Container Shipping
93.21 93.11 93.02 93.31 92.98 92.89 Gold Bugs

我想使用 fscanf 读取此文件单词,将数字放入浮点数组中,将单词放入字符串数组中。但是,经过几个小时的苦思冥想,我仍然不知道如何解决这个问题。

void dataInsert (COMPANY* company1, COMPANY* company2, COMPANY* company3, COMPANY* company4, COMPANY* company5, COMPANY* company6)
{
//Function Declaration
FILE* spData;
float number;
char* name[20];

//Statement
if ((spData = fopen("dataFile","r")) == NULL)
{
    fprintf(stderr, "ERROR OPENING!!");
    exit (1);
}

int i = 0;
int numCount = 0;
int lineCount = 0;
while (fscanf(spData, "%f", &number) != EOF)
{
    if(isdigit(number))
    {
        if (lineCount == 0)
        {
            company1 -> stock_price[i] = number;
        }
        else if (lineCount == 1)
        {
            company2 -> stock_price[i] = number;
        }
        else if (lineCount == 2)
        {
            company3 -> stock_price[i] = number;
        }
        else if (lineCount == 3)
        {
            company4 -> stock_price[i] = number;
        }
        else if (lineCount == 4)
        {
            company5 -> stock_price[i] = number;
        }
        else if (lineCount == 5)
        {
            company6 -> stock_price[i] = number;
        }

        numCount++;
        i++;
        if (numCount == 6)
        {
            lineCount++;
            numCount = 0;
            i = 0;
        }
    }
}//while
fclose (spData);
}//dataInsert

我不知道如何处理每行末尾的字符串。我想将这些字符串放入结构公司->名称[10]中。这些数据位于文本文件中。


而不是使用fscanf我建议使用fgets得到线路。然后使用sscanf在该行上获取数值,并搜索第一个字母字符以了解字符串的开始位置(例如使用strspn http://en.cppreference.com/w/c/string/byte/strspn).

像这样的事情:

char line[256];

while (fgets(line, sizeof(line), fp) != NULL)
{
    /* Get the numbers */
    float numbers[6];
    sscanf(line, "%f %f %f %f %f %f",
        &numbers[0], &numbers[1], &numbers[2],
        &numbers[3], &numbers[4], &numbers[5]);

    /* Where do the numbers end... */
    size_t numbers_end = strspn(line, "1234567890. \t");

    /* And get the name */
    char *name = line + numbers_end;

    /* Do something with the numbers and the name */
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从文本文件中读取字符串和整数 的相关文章

随机推荐