-2

好的,所以这个程序已被缩短以使其更易于阅读。随着变量的数量,显然会有更多的案例陈述。我的问题是为什么我的程序每次运行时都会出错。它编译时很好,但我运行它时不行。

#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
using namespace std;

int main()
{
    string thearray[22960];
    char bigfor[10];
    int arrayvar = 0;
    int finishedarray;
    int a;
    int b;
    int c;
    int d;
    int e;
    int f;
    int g;
    int h;
    int i;
    int j;

    // Constants

    int variable1 = 0;
    int variable2 = 1;
    int variable3 = 2;
    int variable4 = 3;
    int variable5 = 4;
    int variable6 = 5;
    int variable7 = 6;
    int variable8 = 7;
    int variable9 = 8;
    int variable10 = 9;




    for (a = 0; a < 36; a++)
    {
        switch (a)

        {
        case 0:
            bigfor[variable1] = '0';
            break;
        case 1:
            bigfor[variable1] = '1';
            break;
        case 2:
            bigfor[variable1] = '2';
            break;
        case 3:
            bigfor[variable1] = '3';
            break;
        case 4:
            bigfor[variable1] = '4';
            break;
        case 5:
            bigfor[variable1] = '5';
            break;
        case 6:
            bigfor[variable1] = '6';
            break;
        case 7:
            bigfor[variable1] = '7';
            break;
        case 8:
            bigfor[variable1] = '8';
            break;
        case 9:
            bigfor[variable1] = '9';
            break;
        }

        thearray[arrayvar] = bigfor[variable1] + bigfor[variable2] + bigfor[variable4] +
                             bigfor[variable5] + bigfor[variable6] + bigfor[variable7] + 
                             bigfor[variable8] + bigfor[variable9] + bigfor[variable10];


        arrayvar = arrayvar + 1;
    }

    finishedarray = arrayvar + 1;
    ofstream myfile;
    myfile.open("codes.txt");

    for (arrayvar = 0; a < finishedarray; a++)
    {
        myfile << thearray[arrayvar] << endl;
    }

    myfile.close();
    return 0;
}
4

2 回答 2

2

一个问题是您在这里读取未初始化的值:

thearray[arrayvar] = bigfor[variable1]+ bigfor[variable2] + bigfor[variable4] +
bigfor[variable5] + bigfor[variable6] + bigfor[variable7] + bigfor[variable8] + 
bigfor[variable9] + bigfor[variable10];

这是未定义的行为。此时程序中,只有bigfor[variable1]被初始化。

无论您要做什么,我都觉得有一种更简单的方法可以做到。

于 2013-07-15T17:14:20.063 回答
1

问题是你正在做的加法。加法只会添加 ASCII 字符的整数编码值,并产生一个整数。这将导致错误,因为您不能将整数分配给std::string.

除了@juanchopanza 的回答,您的代码还可以大幅改进。例如,您可以在 for 循环中执行此操作,而不是手动列出索引:

std::string bigfor;

for (int a = 0; a < 36; ++a)
{
    bigfor += (a + 48);
}

std::ofstream myfile("codes.txt");

for (int i = 0; i < bigfor.size(); ++i)
{
    myfile << bigfor[i] << std::endl;
}
于 2013-07-15T17:23:54.010 回答