读取整数列表到Array C ++中

时间:2014-11-08 20:21:28

标签: c++ arrays algorithm io

我正在使用C ++编写一个程序来读取文件中的整数,然后将它们传递给检查子集总和的函数。

文件的格式如下:

number of cases n

sum for case 1
list of integers separated by a space

sum for case
list of integers separated by a space

sum for case n
list of integers separated by a space

我现在的问题在于如何将整数列表读入要传递给我的函数的数组中。

到目前为止,这是我的主要内容:

    fstream infile("subset.txt");

    if(infile.is_open()){

    int numCases, num;

    infile >> numCases;

    while(infile >> num){
        for(int i = 0; i < numCases; i++)
        {
            int sum;
            int set[30];

            num >> sum;
            for(int i = 0; i < 30; i++)
            {
                if(num == '\n')
                {
                    sum[i] = -1
                }
                else 
                {    
                    num << sum[i]
                }
            }

               int n = sizeof(set)/sizeof(set[0]);

                if(subsetSum(set, n, sum) == true)
                    printf("True");
                else
                    printf("False");
        }
    }
}

else
    printf("File did not open correctly.");

return 0;

你们可以给我的任何帮助将不胜感激。

是的,这是一项任务,所以如果你愿意给我提示也会受到赞赏。分配是针对算法的,我有这个工作,我只需要一手I / O.

1 个答案:

答案 0 :(得分:1)

我会使用std::getline读取包含数字列表的行,然后使用istringstream来解析该字符串中的数字。

我还使用std::vector代替数组来保存数字。对于实际的解析,我可能会使用一对std::istream_iterator,所以代码看起来像这样:

while (infile >> sum) {
    std::getline(infile, line);
    std::istringstream buffer(line);
    std::vector<int> numbers{std::istream_iterator<int>(buffer), 
                             std::istream_iterator<int>()};

    std::cout << std::boolalpha << subsetSum(numbers, sum);
}
相关问题