0

我正在为游戏开发一个保存文件系统,并试图确保我可以在一个小测试程序中打开文件,确定它是否为空,如果它是空的,则提示用户创建一个角色,如果它not empty 将角色的信息加载到游戏中使用的变量中。到目前为止,在我的测试中,我已经在记事本中创建了文件(将它们留空),使用适当的扩展名保存它们,并尝试打开文件并测试它们是否为空。

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main ( int argc, char* argv[])
{
   struct charFile
   {
      int chapterNum;
      int savePoint;
      string firstName;
      char gender, hairColor, hairType, hairLength, eyeColor, profession, magic, martialSkills;
      bool hasPet;
   } character;

   fstream save;

   char saveFileChoice;
   string saveFile;

   cout << "Select a File (1, 2, 3, 4, 5, or 6): ";
   cin >> saveFileChoice;


   saveFile = saveFileChoice + ".charsav";

   save.open(saveFile.c_str());
   if (!save.good())
   {
      cout << "Save file cannot be opened.\n";
   }

   char tempStr[12];
   save.getline (tempStr, 256);
   if ( tempStr == "EMPTY" )
   {
      cout << "There is no save data in the file.  Starting a new game...\n\n";
      cout << "What is your character's name? ";
      cin >> character.firstName;
      save << character.firstName;

   }

return 0;
}

我想知道为什么即使文件是空的,文件也从未放入 if 语句中,然后即使我在文件中添加了 EMPTY ascii 字符并更改了条件。然后我输入:

if (!save.good())
       {
          cout << "Save file cannot be opened.\n";
       }

并在运行时不断显示消息,因此由于某种原因文件未打开。=/我不知道为什么。

我检查了文件,它们没有被格式化为 .charsav.txt 或任何东西,它们仍然只是 1.charsav、2.charsav 等。我觉得我错过了一些简单而明显的东西。有人可以为我指出吗?

4

1 回答 1

0

if (!strcmp(tempStr, "EMPTY" )) 是您比较字符串的方式

于 2012-08-04T21:53:17.853 回答