看看行
string secondline ("\t<current>" + msg.getCount() + "</current>\n");
"\t<current>"
是const char *
msg.getCount()
看起來像一個int
或size_t
</current>\n
又是一個const char *
將const char *
添加到int
或size_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;
'字符串二線( 「\ t」 + msg.getCount()+ 「 \ n」);'上看看這條線。 –
DimChtz
這些行中有幾行是做指針算術而不是字符串連接。 – Borgleader