2017-07-29 52 views
0
// Update the server status xml 
      string filelocation ("/var/www/html/index.xml"); 
      string firstline ("<server>\n"); 
      string secondline ("\t<current>" + msg.getCount() + "</current>\n"); 
      string thirdline ("\t<highest>" + "--" + "</highest>\n"); 
      string fourthline ("\t<status>Online</status>\n") 
      string finalline ("</server>"); 
      fstream file; 
      file.open(filelocation); 
      file.write(firstline + secondline + thirdline + fourthline + finalline); 
      string updateFlush ("Server Status updated."); 
      printf("%s\n", updateFlush); 
      file.close(); 

請注意,msg.getCount()是同一個文件中的一個函數,用於從中央服務器獲取玩家數量。使用fwrite將服務器狀態轉換爲XML?

發現有關操作數const char *的錯誤。一件用+或做 -

感謝

+0

'字符串二線( 「\ t 」 + msg.getCount()+ 「 \ n」);'上看看這條線。 – DimChtz

+0

這些行中有幾行是做指針算術而不是字符串連接。 – Borgleader

回答

0

看看行

string secondline ("\t<current>" + msg.getCount() + "</current>\n"); 

"\t<current>"const char * msg.getCount()看起來像一個intsize_t </current>\n又是一個const char *

const char *添加到intsize_t創建指向不同地址的新的const char *

同樣的情況,在該行

string thirdline ("\t<highest>" + "--" + "</highest>\n"); 

這裏要添加指針在一起。結果是一個指向或多或少隨機地址的指針。

而在這兩條線:

string updateFlush ("Server Status updated."); 
printf("%s\n", updateFlush); 

您正在創建一個C++字符串對象,並試圖使用C打印功能與需要char *格式字符串進行打印。

您正在將C和C++或基於流的I/O與傳統I/O混合使用。

在當前的C++,你應該這樣來做:

string filelocation ("/var/www/html/index.xml"); 

fstream file; 
file.open(filelocation); 

file 
    << "<server>\n" 
    << "\t<current>" << msg.getCount() << "</current>\n" 
    << "\t<highest>" << "--" << "</highest>\n" 
    << "\t<status>Online</status>\n" 
    << "</server>"; 

string updateFlush ("Server Status updated."); 
cout << updateFlush << std::endl; 

file.close(); 

甚至更​​易讀:

auto file = std::ofstream("/var/www/html/index.xml"); 
file 
    << "<server>" << std::endl 
    << "\t<current>" << msg.getCount() << "</current>" << std::endl 
    << "\t<highest>" << "--" << "</highest>" << std::endl 
    << "\t<status>Online</status>" << std::endl 
    << "</server>"; 

file.close(); 

std::cout << "Server status updated." << std::endl; 

如果用流操作使用std :: ENDL輸出一個換行符。它爲操作系統(CRLF或LF或其他)輸出正確的換行符,並刷新流。

要使用std :: cout,必須包含<iostream>,對於std :: ofstream包括<fstream>

如果你喜歡它的短,你甚至可以做到這一點:

std::ofstream("/var/www/html/index.xml") 
    << "<server>" << std::endl 
    << "\t<current>" << msg.getCount() << "</current>" << std::endl 
    << "\t<highest>" << "--" << "</highest>" << std::endl 
    << "\t<status>Online</status>" << std::endl 
    << "</server>"; 

std::cout << "Server status updated." << std::endl;