2014-02-10 36 views
2

我用下面的代碼嘗試:C++ fprintf中只打印第一個字符串

String hi = "hi"; 
String bye = "bye"; 
fprintf(fileout, "%d: %s, %s", 10, hi, bye); //fail 
fprintf(fileout, "%d: %s, %s", 10, "hi", "bye");//ok 

但是,這不能寫喜告別了文本文件。哪裏不對?

回答

5

fprintf和相關功能是C函數。

您需要一個「C字符串」,它是一個以空字符結尾的字符數組(char *char const *),而不是C++字符串(std::string)。

fprintf(fileout, "%d: %s, %s", 10, hi.c_str(), bye.c_str()); 

請參閱fprintfc_str()

雖然C++代碼通常會使用C++ I/O functions

+0

雖然,請注意,manhon使用的'String'可能不是'std :: string'。請注意,大小寫不同。 manhon,檢查你的String類是否有類似於'std :: string :: c_str()'的成員函數並嘗試使用它。 – chwarr

+0

是的,@ c45207說得很好。尋找一個返回'char *'(或'const char *'或'char const *')的函數。 –

+0

感謝您的幫助。 bye.c_str()解決了我的問題。非常感謝你! – manhon

0

您通常不希望在C++中使用fprintf和company。

fileout << 10 << ": " << hi << ", " << bye; 
+0

我使用fprintf becoz我正在嘗試將浮點數編寫爲文件,其中一些是舍入到數字,一些舍入爲小數點後兩位。 – manhon

+0

@manhon:然後你會想查找'std :: setw'和'std :: setprecision'。 –