【问题标题】:Stack overflow error during recursion递归期间的堆栈溢出错误
【发布时间】:2015-02-08 08:58:40
【问题描述】:

我要为这个程序工作而大发雷霆。快到了!我认为....我只是有一个堆栈溢出错误需要解决。代码如下:

using namespace std;

struct runner{
public:
    int position;
    string time;
    int age;
    string sex;
    string gender;
    string firstName;
    string lastName;
    string city;
    string state; 


runner(){
    runner r1;
    string dataChunk;
    int ageTotal = 0;
    double ageAverage = 0.0;
    int ageCount = 0;
    int femaleAlabama = 0;
    int femaleOverForty = 0;
    int femaleHuntsville = 0;
    int femaleCount = 0;
    double femaleAgeAverage = 0.0;

    ifstream inFile("C:\\Users\\Anthony\\Desktop\\cmarathon.csv");


        getline(inFile, dataChunk, ',');
        r1.position = atoi(dataChunk.c_str());

        getline(inFile, dataChunk, ',');
        r1.time = dataChunk;

        getline(inFile, dataChunk, ',');
        r1.age = atoi(dataChunk.c_str());
        ageTotal = +age;
        ageCount = +1;

        getline(inFile, dataChunk, ',');
        r1.sex = dataChunk;
        if(sex == "f" || "F")
            femaleCount++;
            femaleAgeAverage++;

        getline(inFile, dataChunk, ',');
        r1.gender = dataChunk;

        getline(inFile, dataChunk, ',');
        r1.firstName = dataChunk;

        getline(inFile, dataChunk, ',');
        r1.lastName = dataChunk;

        getline(inFile, dataChunk, ',');
        r1.city = dataChunk;

        getline(inFile, dataChunk, ',');
        r1.state = dataChunk;

        if(sex == "f" || "F" && age > 40)
            femaleOverForty++;

        if(sex == "f" || "F" && city == "Huntsville")
            femaleHuntsville++;

        if(sex == "f" || "F" && state == "Al" || "AL")
            femaleAlabama++;
        cout<<r1.position<<" "<<r1.time<<" "<<r1.age<<" "<<r1.sex<<" "
            <<r1.gender<<" "<<r1.firstName<<" "<<r1.lastName<<" "<<r1.city
            <<" "<<r1.state<<endl;}

};




int main(){

int i;
    for(i = 1; i <1343; i++){
        runner();
    }







    system("PAUSE");
    return 0;

}

这里的目标是遍历 .csv 工作表并将数据提取到结构中。然后我可以使用这些数据来计算各种东西,比如女性的平均年龄等。有什么建议吗?

编辑:

这是我尝试运行程序时收到的错误代码的 sn-p

【问题讨论】:

  • #include "vector"; 应该是 #include &lt;vector&gt; 和其他所有类似的。
  • 请添加任何错误消息、日志或类似内容。你试过调试器吗?
  • 您有一个名为 runner 的结构和该结构中的一个函数,也称为 runner。您的变量在函数内部声明,因此每次运行时它们都会被销毁并重新创建。 1343这个数字是从哪里来的?这会运行吗?尝试使用调试器或添加一些控制台输出,因为我认为这不会像您认为的那样。
  • 性 == "f" || "F" 不起作用,这将被读作 (sex == "f") || “F”:en.cppreference.com/w/cpp/language/operator_precedence
  • "femaleAgeAverage++;"每次都会运行。在 IF 语句之后,您需要将要运行的行括起来。

标签: c++ loops recursion structure stack-overflow


【解决方案1】:

问题
不要在构造函数中创建runner r1;,否则会导致无限递归。

解决方案
您可以将 r1 设为静态或对现有对象的引用。以runner &amp;r1 = *this; 为例。

【讨论】:

  • 类和结构都创建对象。有关差异的问答,请参阅this SO question。
  • 这帮助了很多人。我想我现在正在修复它。谢谢
猜你喜欢
  • 1970-01-01
  • 2018-03-10
  • 2014-08-27
  • 2016-11-11
  • 2020-09-23
  • 1970-01-01
  • 2015-06-17
  • 1970-01-01
  • 2016-12-30
相关资源
最近更新 更多