0

I can't seem to figure out why my program is crashing. When I remove the while loop under "//Displays name options" The program runs fine. The code compiles on GCC with no warnings. Could it be my compiler? Does it have something to do with fstream? Help would be appreciated.

Oh yea. If your wondering this program will read data.txt and Load the appropriate data to an instance of the player function. It is in a incomplete state at the moment.

#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 \ 

1 Answer 1

3

Using your debugger would've uncovered this, or simply using some cout statements.

When you declare i in the following manner:

int x,i,lineNum = 0; 

You declare 3 int and initialise lineNum to 0; however the other two remain unitialised, and therefore it's undefined behaviour to use them.

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

Prefer to declare and initialise one variable per line, like so:

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

The use of auto also forces you to initialise them to a value.

If you wanted to write it all on one line, you'd have to write

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

But it's just not as readable and no one will thank you for it.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow that really helped. I would up vote but this is one of my first questions. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.