Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

c++ - concatenate two char arrays into single char array using pointers

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...