純C/C++ sprintf/snprintf()函數 [類似C# String.Format 字串組合]

純C/C++ sprintf/snprintf()函數 [類似C# String.Format 字串組合]

純C/C++ sprintf/snprintf()函數 [類似C# String.Format 字串組合]


資料來源:https://openhome.cc/Gossip/CGossip/SscanfSnprintf.html

http://www.cplusplus.com/reference/cstdio/snprintf/


線上編譯器: https://www.tutorialspoint.com/compile_c_online.php


code:

#include <stdio.h>

int main(void) {
	char buf[80];

	char buffer [100];
	int cx;
	
    sprintf(buf, 
        "%d %f %s %d %d %d %s", 
        25, 54.32E-1, "Thompson", 56, 789, 123, "56"
    );//起始指標位置,"字串格式",填入值
	
    printf("%s\n", buf);

	cx = snprintf ( buffer, 100, "The half of %d is %d", 60, 60/2 );
	//起始指標位置,可用記憶體長度,"字串格式",填入值
	if (cx>=0 && cx<100)// check returned value
	{
		snprintf ( buffer+cx, 100-cx, ", and the half of that is %d.", 60/2/2 );
		//起始指標位置,可用記憶體長度,"字串格式",填入值
	}   
	printf("%s\n", buffer);
    return 0;
}
/*
25 5.432000 Thompson 56 789 123 56
The half of 60 is 30, and the half of that is 15.
*/

One thought on “純C/C++ sprintf/snprintf()函數 [類似C# String.Format 字串組合]

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *