Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   a little pointer problem (http://www.programmingforums.org/showthread.php?t=13267)

cwl157 Jun 1st, 2007 11:17 PM

a little pointer problem
 
Alright so I have a program that takes 2 player names and turns it into a file name. The file name looks like playerName1-playerName2.save. It then takes this file and searches the directory for it. If it finds it in the directory it is supposed to load the player names and the scores into local variables in main. It appears to load the names correctly but i can not figure out how to load the scores. I have a seperate function that goes through the file and picks out the names and scores from the file. Now i just need to figure out a way to get all of that into the local variables in main. I am pretty sure it can be done with pointers and pass by reference and by using &. Any help is appreciated.
Here's the code:
:

#include <iostream>
#include <malloc.h>
#include <tchar.h>
#include <wchar.h>
#include <string.h>
#include <windows.h>

using namespace std;

#define BUFFER_SIZE 200
#define SPACE ' '
#define NEW_LINE '\n'

void getName(char *fileName);

bool doesFileExist(char *fileName)
{
  WIN32_FIND_DATA FindFileData;
  HANDLE hFind;
  bool isFileFound = false;
 char directory[BUFFER_SIZE] = ".\\\\*";
  LPTSTR DirSpec;
  DWORD dwError;

  DirSpec = (LPTSTR) malloc (BUFFER_SIZE);

  printf ("looking for file: %s ...\n", fileName);
  hFind = FindFirstFile(directory, &FindFileData);
  if (hFind == INVALID_HANDLE_VALUE)
  {
    printf ("Invalid File Handle. GetLastError reports %d\n", GetLastError ());
  } // end if
  else
  {

    while (FindNextFile(hFind, &FindFileData) != 0)
      {
        if (strcmp(FindFileData.cFileName, fileName) == 0)
        {
            //getName(fileName);
            isFileFound = true;
        } // end if
        else
        {
          // empty else
        } // end else
     
      }  // end while 

      dwError = GetLastError();
      FindClose(hFind);
      if (dwError != ERROR_NO_MORE_FILES)
      {
        _tprintf (TEXT("FindNextFile error. Error is %u.\n"), dwError);
        return (-1);
      } // end if
  } // end else

  return isFileFound;
} // end doesFileExist

void getName(char *fileName)
{
  FILE *inputFile;
  int lineIndex = 0;
  int nameIndex = 0;
  char name[BUFFER_SIZE];
  char line[BUFFER_SIZE];
  char playerOneName[BUFFER_SIZE];
  char playerTwoName[BUFFER_SIZE];
  char playerOneTotalWinsStr[BUFFER_SIZE];
  char playerTwoTotalWinsStr[BUFFER_SIZE];
  char tempName[BUFFER_SIZE];
  char scoreStr[BUFFER_SIZE];
  char tempScoreStr[BUFFER_SIZE];
  int scoreIndex = 0;
  int fileLineCount = 0;
  int playerOneTotalWins;
  int playerTwoTotalWins;
  int savedLineIndex = 0;


  inputFile = fopen(fileName, "r");

  fgets(line, BUFFER_SIZE, inputFile);
  while (!feof(inputFile))
  {
    lineIndex = 0;
    while (lineIndex < strlen(line))
    {
        nameIndex = 0;
        scoreIndex = 0;
        while (line[lineIndex] != SPACE)
        {
         
          name[nameIndex] = line[lineIndex];
          strcpy(tempName, name);
          strcpy(line, "");
          nameIndex++;
          lineIndex++;
        } // end find space while
        tempName[nameIndex] = '\0';

        savedLineIndex = lineIndex; 
   
        while (line[savedLineIndex] != NEW_LINE)
        {
          scoreStr[scoreIndex] = line[savedLineIndex];
          strcpy(tempScoreStr, scoreStr);
          strcpy(line, "");
          scoreIndex++;
          savedLineIndex++;
        }
        tempScoreStr[scoreIndex] = '\0';

        if (fileLineCount == 0)
        {
            strcpy(playerOneName, tempName);
            strcpy(playerOneTotalWinsStr, tempScoreStr);
        }
 
        else if (fileLineCount == 1)
        {
          strcpy(playerTwoName, tempName);
          strcpy(playerTwoTotalWinsStr, tempScoreStr);
        }

    } // end lenght of line while

    fgets(line, BUFFER_SIZE, inputFile);
    fileLineCount++;
  } // end feof while

  playerOneTotalWins = atoi(playerOneTotalWinsStr);
  playerTwoTotalWins = atoi(playerTwoTotalWinsStr);
} // end getName

void loadFile(char *playerOneName, char *playerTwoName, int playerOneTotalWins, int playerTwoTotalWins)
{
  char fileName[BUFFER_SIZE];
  //char playerOneName[BUFFER_SIZE];
  //char playerTwoName[BUFFER_SIZE];
 
  while (true)
  {
    cout << "Please enter player 1's name: ";
    cin >> playerOneName;
    cout << "Please enter player 2's name: ";
    cin >> playerTwoName;
    sprintf(fileName, "%s-%s.save", playerOneName, playerTwoName);
    if (doesFileExist(fileName))
    {
        break;
    }
    else
    {
      printf("File not found\n");
    } // end else
  } // end while
}
 
int main()
{
  char playerOneName[200];
  char playerTwoName[200];
  int playerOneTotalWins = 0;
  int playerTwoTotalWins = 0;

  loadFile(playerOneName, playerTwoName, playerOneTotalWins, playerTwoTotalWins);

  cout << "player one is: " << playerOneName << endl;
  cout << "Player one score is: " << playerOneTotalWins << endl;
  cout << "Player two is: " << playerTwoName << endl;
  cout << "Player two score is: " << playerTwoTotalWins << endl;
  scanf("%s");
  return 0;
} // end main


The input file has a name and then a space and then the score so it looks like this:
:

sean 45
brad 16

So the file name for this file would be sean-brad.save
I tested these function seperately so i know they will find the file and extract the information correctly now i just need to figure out how to assign that information to the local variables in main.

And please note the line
:

scanf("%s")
is just there so the window will stay open.

DaWei Jun 2nd, 2007 12:40 AM

Any particular reason you're mixing C and C++? It makes for a poor C program and a poor C++ program.

cwl157 Jun 2nd, 2007 1:18 AM

well i have to search the directory and the only way i know how to do that is in C and then the C++ part i had before that. So i guess it just kinda happened that way. Isn't the C just mainly the printf() that i used instead of cout? I didn't think it mattered that much if i mixed the 2.

grumpy Jun 2nd, 2007 2:13 AM

Technically, most compilers don't care all that much if you mix C and C++, as long as you don't hit on incompatibilities between the languages. However, the languages have some subtle and not-so-subtle incompatibilities. So mixing C and C++ tends to give code that is much harder to get right (and you're having trouble getting your code working right), and also much harder for some poor sucker in future (who may even be yourself) to maintain. Code which is more likely to be incorrect, or more likely to break if you try to modify it, is viewed by most people as poor code.

There is more vanilla C in your code than using printf(). strcpy(), feof(), sprintf() are also in the standard C library, and most parts of the C library are deprecated (i.e. their usage is discouraged) in C++, as C++ provides alternate methods.

Incidentally, scanf("%s") formally yields undefined behaviour according to the C standard (because the %s format descriptor causes the function to expect there to be a second argument, and that second argument is written to).

To get values from a function back to main(), you need to do one of;

1) return the values to main()

2) move the values to some global area, which is accessed by both your function and by main()

3) pass pointer arguments to the function, so your function can modify whatever the pointer points at, and main() can see the corresponding variables change.

cwl157 Jun 2nd, 2007 2:24 AM

alright, I'll clean up the C part and make it all C++. I just used the sprintf and feof cause i took a class in C las semester and I know thats a way to put together strings and find the end of a file. I dont know how to do that same thing in C++ although its probably easier, I just don't know how to do it so i went with what i knew and what i already had examples of how to do it. Now on to the other part. The third point you made:
Quote:

3) pass pointer arguments to the function, so your function can modify whatever the pointer points at, and main() can see the corresponding variables change.
That's what I need to do so main can see the variable change that the function made. I know it would be easy to have global variables but I've heard thats not good programming practice either. So how would i do that? Do i use type int * as the function parameters so then the function knows its a pointer? And then when i call the function don't i have to pass something else besides just the normal name so it can see the corresponding changes like you said? I know i've done things like this before with passing by reference or whatever its called but i just can't remember exactly how its done.

DaWei Jun 2nd, 2007 9:53 AM

:

#include <iostream>
#include <sstream>
#include <string>

using std::string;
using std::stringstream;
using std::cout;
using std::endl;

// Return a value using return
string getPlayerName ()
{
    return "Billy Bob";
}
// Return values using pointers
bool getPlayerNames (string* name1, string* name2)
{
    // If getting the names fails in some way,
    // tell the caller
    if (0)
    {
        return false;
    }
    *name1 = "Billy Bob";
    *name2 = "Nancy Bob";
    return true;
}
// Return converted scores using references
bool getScores (int& score1, int& score2)
{
    stringstream s1 ("30 97");
    s1 >> score1 >> score2;
    if (s1.fail ())
        if (!s1.eof ()) return false;
    return true;
}

int main (int argc, char * const argv[])
{
    string name1, name2;
    int score1, score2;
    cout << getPlayerName () << "\n";
    if (getPlayerNames (&name1, &name2)) cout << name1 << ", " << name2 << "\n";
    else cout << "Failed to get names\n";
    if (getScores (score1, score2)) cout << score1 << ", " << score2 << endl;
    else cout << "Failed to get scores";
    cout << endl;
 
    return 0;
}

Quote:

Originally Posted by Output
Billy Bob
Billy Bob, Nancy Bob
30, 97



All times are GMT -5. The time now is 2:43 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC