![](/img/trans.png)
[英]Convert char String to an int but not possible to convert a char from an char string to an int?
[英]Making a char string from char[ ] and int
我想做的是用兩個變量創建一個字符串 str ,這樣我就可以在上面使用各種 string.h 函數。 這是我到目前為止得到的,但它返回了一個 null 字符串。
size_t length = strlen(name) + sizeof(int) + 1;
char *player = malloc(length);
snprintf(player, length, "%s %d\n", name, score);
並給定另一個具有相同格式的字符串,然后我對它們使用 strcmp ,如下所示:
if (strcmp(line, player) < 0)
{
fprintf(fcopy, "%s %d\n", name, score);
}
else
{
fputs(line, fcopy);
}
我正在嘗試編寫的 function 從結構如下的 txt 文件中獲取“行”輸入:
約翰 50
亞倫 45
所以我需要播放器字符串具有相同的格式。 希望這很清楚,我很抱歉,但我是一個新手,我剛剛開始進入 C 並使用 stackoverflow。
如果你使用動態分配,最簡單的就是讓snprintf
給你長度:
// calling with NULL,0 and it returns the count of character that
// __would__ have been written to the buffer
int len = snprintf(NULL, 0, "%s %d\n", name, score);
char *player = malloc(len + 1);
snprintf(player, len, "%s %d\n", name, score);
...
free(player); // remember to pick out the trash
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.