繁体   English   中英

这个循环如何使我的程序崩溃?

[英]How is this loop crashing my program?

我似乎无法弄清楚为什么我的程序崩溃了。 当我删除“ //显示名称选项”下的while循环时,程序运行正常。 该代码在GCC上编译,没有任何警告。 可以是我的编译器吗? 它与fstream有关吗? 帮助将不胜感激。

哦,是的 如果您想知道该程序将读取data.txt并将相应的数据加载到播放器功能的实例。 目前处于不完整状态。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
#define cls system("cls");

bool Pload = false;

void menu();

struct player {
    int Px, Py, life = 20;
    string name = "";
};

main() {
    menu();
}

void menu() {
    string cLine,names,input;

    int x,i,lineNum = 0;
    fstream data;

    menu:

    data.open("data.txt");
    //Gets list of all names in data.txt, Adds them to string names
    while(data.good()) {
        getline(data,cLine);
    if(cLine[0] == '/') {
        names += cLine;
    }
}           
names += '\n';

//Displays name options
cls
cout << "Welcome to  W A L K.\n\nWhat is your name?\n";
while(names[i] != '\n') 
{
    cout << i; 
    if(names[i] == '/') {cout << endl;i++;} else {cout << names[i];i++;}
}
cout << endl;
getline(cin,input);

//checks if name exits and loads file data into player/world objects 
data.close();
data.open("data.txt");
while(data.good()) {
    lineNum++;
    getline(data,cLine);
    if(cLine.erase(0,1) == input) {
        cls cout << "Found Name" << endl;
        getline(cin, input);

        }

    }
//Restarts menu
data.close();
goto menu;
}

data.txt中

/Sammy
x:0
y:0
l:20
\

/Mary
x:7
y:9
l:20
\


/Dill
x:7
y:9
l:20
\

/Jack
x:7
y:9
l:20
\

使用调试器可以发现这一点,或者仅使用一些cout语句即可。

当您以以下方式声明i时:

int x,i,lineNum = 0;

您声明3 int并将lineNum初始化为0 ; 但是其他两个仍然统一,因此使用它们是不确定的行为。

while(names[i] != '\n') // UB, i is unitialised

最好每行声明和初始化一个变量,如下所示:

auto x = 0;
auto i = 0;
auto lineNum = 0;

使用auto也会迫使您将它们初始化为一个值。

如果要全部写在一行上,则必须写

auto x = 0, i = 0, lineNum = 0;

但这不是那么可读,没有人会感谢你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM