我正在编写一个客户端程序和服务器程序。在服务器程序上,为了将结果写回客户端,我必须将字符串转换为 const char* 以将其放入 const void* 变量中以使用 write() 函数。当我检查时,字符串本身正在输出正确的结果,但是当我对字符串使用 c_str() 函数时,它只输出到字符串中的第一个变量。我提供了一些代码供参考(不确定这是否有意义)。
我已经尝试了各种不同的方法来调整字符串,但还没有任何效果。
以下是变量的声明方式:
string final;
const void * fnlPrice;
carTable* table = new carTable[fileLength];
这是表的结构:
struct carTable
{
string mm; // make and model
string hPrice; // high price
string lPrice; // low price
};
下面是有问题的代码片段,首先更新字符串变量 final,使用文本以及生成的字符串变量:
final = "The high price for that car is $" + table[a].hPrice + "\nThe low
price for that car is $" + table[a].lPrice;;
if(found = true)
{
fnlPrice = final.c_str();
n = write(newsockfd,fnlPrice, 200);
if (n < 0)
{
error("ERROR writing to socket");
}
}
else
{
n = write(newsockfd, "That make and model is not in
the database. \n", 100);
if (n < 0)
{
error("ERROR writing to socket");
}
}