Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to take a text file with names (ex: john doe) and fin the first name and last name. Then, I want to take these two char arrays and concatenate them together using pointers. The code that is commented out is working code that takes the two char arrays and puts them into a single char array ie concatenating them together. This project requires that I use pointers, and that I use char arrays I am not asking for you to do it for me, but please help me realize what I am doing wrong. Thanks

EDIT: the error I am getting is a seg fault..so Im thining my playerPtr is going out of bounds somewhere??

void readPlayer(char *finName2, player *playerPtr)
{
player *playerHome = playerPtr;
ifstream fin;
char *tempfName= new char[20];
char *templName= new char[20];
char *tempName= new char[20];
char *tempNameHome = tempName;
fin.open(finName2);

if(!fin.good())
{
cout << "Error with player file!" << endl;       
}
else
{
fin >> tempfName;
fin >> templName;  //prime file
cout << tempfName << templName;
while(fin.good())
{
  for(int i =0;i<5;i++)
  {
    //find the length
    //int index =0, length=0;
while(*tempfName != '')
    //while(tempfName[length] != '')
{

      tempfName++;
}
      strcopy(tempName,tempfName);

  //now add space after first name
     *tempName = ' ';
      tempName++;
      //tempfName[length] = ' ';
      //tempfName++;
      //length++;

      while(*templName != '')
    //while(templName[index] != '')
  {
        templName++;
    //tempfName[length] = templName[index];
    //length++;
    //index++;
  }
      strcopy(tempName,templName);
      //tempName++;
      //tempfName[length]='';          
      strcopy((*playerPtr).name,tempName);
      playerPtr++;
  fin >> tempfName;
  fin >> templName;
      }
   }
}
delete[] tempfName;
delete[] templName;
delete[]tempName;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
288 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your tempfName & templName are incremented all the time and they move beyond their allocated memory. you need to reset their position.
Plus I can see that the

fin >> tempfName;
fin >> templName;

is inside the for loop, which means fin.Good is only checked once every 5 times.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...