SkippyNBS
SkippyNBS

Reputation: 777

Global String Array in C++

I was writing some code in C++ to practice making functions and I ran into the problem of having an array of strings where I wanted to define specific elements in one function, then output those elements in another function. I have only done the code for the input part so far. When I run the program, it stops responding when it asks for the player name the second time. I have my array, p[1], defined as std::string because otherwise I get an error when I try to run getline(cin, p[x]). Any insights on why the program stops running and how to create the array I want?

My code:

#include <stdio.h>
#include "simpio.h"
#include "strlib.h"
#include "iostream.h"

int Hp[1], Atk[1], Ddg[1];
std::string p[1];

void player(int x){
    cout<<"Player name: ";
    getline(cin, p[x]);
    cout<<"\tHp: ";
    cin>>Hp[x];
    cout<<"\tAtk: ";
    cin>>Atk[x];
    cout<<"\tDdg: ";
    cin>>Ddg[x];
    }

main(){
   string go;

   player(0);
   player(1);

   cout<<"Go? (Yes/No): ";
   cin>>go;
   cin.get();

}

Upvotes: 0

Views: 932

Answers (1)

herohuyongtao
herohuyongtao

Reputation: 50667

You need to change

std::string p[1];

to

std::string p[2]; // have size=2 (at least) so you can access p[1] later

Upvotes: 1

Related Questions