如何将大量的数字列入c ++代码

我有四个列表,每个列表包含84个不同的速率,我希望能够使用基于input信息的if / else语句访问,我希望有比键入每个数组更有效的东西。

最简单的方法是什么? 任何提示将是非常有益的,我只需要一个起点。

#include "MaleNonSmoker.txt" using namespace std; double ratesmn[85] = { #include "MaleNonSmoker.txt" - 1 }; #include <iostream> #include <string> #define STARTAGE 15 int main() { double const *rates; rates = ratesmn; int age; cout << "How old are you?\n"; cin >> age; double myrate = ratesmn[age - STARTAGE]; return 0; } 

我得到的错误是从第1行:语法错误:'常量'和第7行:'太多初始化'

如果这些数字没有改变,就没有必要在运行时从文件中读取数字。 你也可以在编译时使用它们。

使用任何你喜欢的工具创build四个文件的数组,但每个数字后面的逗号,所以它看起来像这样:

 51, 52, 53, 

在您的c ++代码中,定义4个数组,并使用#include包含文本文件中的数字;

 int ratesms[85] = { #include "ratesms.txt" -1 // add another number because the txt file ends with a comma }; 

对其他arrays做同样的事情。

例如,在代码中确定要使用哪个列表,并设置指向该列表的指针

 int const *rates; if ( /* smoking male */ ) rates = ratesms; else if ( /* other variations */ ) rates = ... 

然后像这样使用它;

 #define STARTAGE 15 int age=35; // example int myrate=rates[age-STARTAGE]; 

如果您不想从数组索引中减去开始时间,则还可以将15个虚拟数字添加到数组中;

 int ratesms[100] = { 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, #include "ratesms.txt" -1 // add another number because the txt file ends with a comma }; 

现在ratesms[15]将包含txt文件中的第一个数字。

你可以像这样在C ++中定义一个数组的数组:

int[6] rates = {1, 2, 3, 4, 5, 6};

你的“名单”的格式是什么?

阅读它们应该非常简单 – 在C ++中查看这个教程的文件I / O。 如果将列表保存为简单的.txt文件,则可以通过创build一个ifstream并调用getline()逐行读取每个列表项。 文件数据将作为string读取,因此可以使用stoi()和stod()分别将它们转换为整数和双精度(查看string引用以获取更多转换方法)。

你也可以考虑将你的excel文件保存为逗号分隔值(.csv)文件,然后以相同的方式逐行读取。 每行代表一行,单元格的值用逗号分隔,非常容易parsing。