我有一个 char *
,我需要将一个字符替换为 double 值(未知位数)。所以我认为我需要计算位数,然后创建一个 realloc() 并替换字符。我只是不确定如何计算位数并进行此替换
。
例如:
char *c = strdup("a+b");
double d = 10;
//I'd like to replace 'a' for 10.
//then 'c' would be : 10+b.
//Next iteration I need to change the 'b' value then I get:
//c = 10 + 3
最佳答案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
const char* s = "a+b";
double d = 10.23142;
//determine the string length needed for printing d
size_t n = snprintf(NULL, 0, "%g", d);
// old string length + n - 1 for replaced b + 1 for '\0'
char* new_s = malloc( strlen(s) + n - 1 + 1);
//write the double
sprintf(new_s, "%g", d);
//skip the first byte (where b is) at the source and the double's length at the destination
strcpy(new_s + n, s + 1);
printf("%s\n", new_s); //prints 10.2314+b
free(new_s);
return 0;
}
在这种指针算术中很容易出现差一错误,因此像 gcc 的 mudflap 或 AddressSanitizer 这样的东西对于检查以确保程序不会在某些地方进入未定义的行为非常有用。
如果可以的话,最好使用 C++,这样您就不必担心此类问题:
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
string s = "a+b";
double d = 10.23142;
s.replace(0,1,to_string(d));
cout<<s<<endl;
return EXIT_SUCCESS;
}
关于c - 将 char* 中的字符替换为 double 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31363099/