Call function from function - how to pass correctly

3121 views c++
-1

I'm having a lot of trouble with trying to write the syntax for one of my codes.

The main problem I'm having is calling the trimField() function

The trimFrield() function is called from my csvRecord transformDataToCSV() function, which is a structure type. Those are the variables being passed to trimField(). Here it what I have so far:

// For the required data members, Name, Id, Score, call trimField function to remove trailing
// spaces and place data into csvRecord, copy entire array of answers to csvRecord and return record


csvRecord transformDataToCSV(Scantron &inputRecord){
    csvRecord outputRecord;
    trimField(inputRecord.Name[21], outputRecord.Name[21]);
    trimField(inputRecord.Id[11], outputRecord.Id[11]);
    trimField(inputRecord.score[4], outputRecord.score[4]);
    for(int i = 0; i < 60; ++i){
        outputRecord.answerArray[i] = inputRecord.answerArray[i];
    trimField(inputRecord.answerArray[61], outputRecord.answerArray[61]);
    }
return outputRecord;
}


// Remove trailing spaces from fieldIn cstring and place in fieldOut cstring
// If entire field is blank place one space followed by '\0'
void trimField(char fieldIn[], char fieldOut[] )   {
    for(int i = 0; i < 150; i++)    {
        if(fieldIn[i] != ' ')   {
            strncpy(fieldIn, fieldOut, 150);
        }
    }
}

answered question

1 Answer

4

Your trimField function should probably return the trimmed data.

As i stands it returns void and takes all arguments by value, so there's no way it can modify anything from the callers perspective.

If you don't want to return the modified data (although I don't see why not), you could make your function take a pointer or reference to the data so it can modify what the caller passed in. That is usually a bad idea though since it is somewhat error prone and can be confusing to users. But it is an option.

You probably also want to rethink your use of C-style arrays and consider using std::array or std::vector instead.

posted this

Have an answer?

JD

Please login first before posting an answer.