【问题标题】:Reading list of integers into an Array C++将整数列表读入数组 C++
【发布时间】:2014-11-08 20:21:28
【问题描述】:

我正在使用 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 方面的帮助。

【问题讨论】:

  • num == '\n' 不起作用,因为您正在读取一个 int,而不是一个字符。也许使用 getline。

标签: c++ arrays algorithm io


【解决方案1】:

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

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

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);
}

【讨论】:

    猜你喜欢
    • 2021-04-06
    • 2014-04-08
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多