Write a function in C++ called parseLine that has the following 4 parameters: char…
- User
Write a function in C++ called parseLine that has the following 4 parameters: char currentGame[], char opponentName[], int* homeScore, int* opponentScore. currentGame will hold a string in the following format: opponent name,homeScore-opponentScore. Parse the opponent name from the string and save it to the second parameter then parse the home score and opponent score saving them to the 3rd and 4th parameter. This function should be of the integer data type and return 0 if the line is parsed successfully and 1 if it fails to parse the information.
- Assistant
Here's a C++ function that meets your requirements:
cpp#include <cstring> #include <cstdlib> int parseLine(char currentGame[], char opponentName[], int* homeScore, int* opponentScore) { // Find the comma separating the opponent name and scores char* commaPos = strchr(currentGame, ','); if (commaPos == nullptr) { return 1; // Failed to find the comma } // Copy the opponent name strncpy(opponentName, currentGame, commaPos - currentGame); opponentName[commaPos - currentGame] = '\0'; // Ensure null-termination // Find the hyphen separating the scores char* hyphenPos = strchr(commaPos + 1, '-'); if (hyphenPos == nullptr) { return 1; // Failed to find the hyphen } // Parse the home score *homeScore = atoi(commaPos + 1); // Parse the opponent score *opponentScore = atoi(hyphenPos + 1); return 0; // Successfully parsed the line }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.