Strok空间使用缓冲区/动态内存

时间:2016-03-07 18:50:05

标签: c arrays pointers dynamic strtok

从缓冲区读取数据时,我怎么能在空格中进行操作?如果我的文本文件包含

1 23 50

45 50 30

2 15 30

我决定用下面的代码打印数组,它将逐行打印。我怎么能扩展它以进一步将数组划分为数组的每个索引的单个数字?例如

1

23

50等等...

我尝试过使用strtok,但我一直在使用segfaulting,而且我不确定在哪里修复它。

enum AudioTypes

2 个答案:

答案 0 :(得分:2)

  

我想要wholeFile [0] = 1,wholeFile 1 = 23

这可以通过fscanf轻松完成。 Here是输入扫描的一个很好的参考。

package pizza;

import java.util.Scanner;

public class Pizza {

public static void main(String[] args) {
    Double diameter;
    Double radius;
    Double cost;
    Double area;
    final Double costPerInch;

    //Ask and enter diameter
    System.out.println("What is the diameter?");
    Scanner size = new Scanner(System.in);
    diameter = size.nextDouble();
    size.close();
    radius = diameter / 2;

    //Ask and enter price
    System.out.println("What is the price of the pizza?");
    Scanner price = new Scanner(System.in);
    cost = price.nextDouble();
    price.close();

    //Calculate cost per inch
    area = radius * Math.PI;
    costPerInch = cost / area;

    //Output results
    System.out.println("The cost per inch of the pizza is" + costPerInch);

如果您想以数组形式使用它,请添加递增整数并将保持更改为数组。

#include <stdio.h>

int main(){

    FILE *in = fopen("in.txt" , "r");
    int hold;

    /* Won't actually store values, but can be used for
       value manipulation inbetween */

    while ( fscanf(in, "%d", &hold) != EOF ){
        printf("Scanned in %d\n", hold);
    }

    fclose(in);

    return 0;

}

您也可以像这样进行动态内存分配:

#include <stdio.h>

int main(){

    FILE *in = fopen("in.txt" , "r");
    int hold[100], i=0; // Hold a maximum of 100 integers

        while ( fscanf(in, "%d", &hold[i]) != EOF ){
            printf("Scanned in %d\n", hold[i++]);
        }

        fclose(in);

    return 0;

}

答案 1 :(得分:0)

这将在您的文件的每一行读取1,2或3个数字。它使用sscanf的返回值来查看每行读取的数量。当然,如果有任何流氓非数字数据,它会搞砸。

#include <stdio.h>

int main(void)
{
    FILE *fp;
    int a, b, c;
    int res;
    char str [100];
    if ((fp = fopen("file.txt", "rt")) == NULL)
        return 1;

    while(fgets(str, sizeof str, fp) != NULL) {
        res = sscanf(str, "%d%d%d", &a, &b, &c);
        if (res == 3)
            printf ("3 values %d %d %d\n", a, b, c);
        else if (res == 2)
            printf ("2 values %d %d\n", a, b);
        else if (res == 1)
            printf ("1 value %d\n", a);
        else
            printf ("0 values\n");
    }

    fclose(fp);
    return 0;
}

文件内容:

1 23 50
45 50 30
2 15 30
10 20

100

节目输出:

3 values 1 23 50
3 values 45 50 30
3 values 2 15 30
2 values 10 20
0 values
1 value 100