简体   繁体   English

需要帮助格式化字符串输出

[英]Need help formatting a string output

vector<data> getList = readContent();
string output = "";
ostringstream conv;
istringstream is;

output += "s: 200 OK\nThe list of records in the book:\n";

for(int j = 0; j < getList.size(); j++)
{
 conv << getList[j].record;

 output += conv.str();
 output += "     ";
 output += getList[j].fName;
 output += " ";
 output += getList[j].lName;
 output += "     ";
 output += getList[j].phoneNum;
 output += "   \n";

 conv.str("");
}

send(s, (char *)output.c_str(), strlen((char *)output.c_str()), 0);

readContent() returns a vector containing all the data that is read from a file. readContent()返回一个向量,该向量包含从文件读取的所有数据。 This is printing everything that is in the vector. 这将打印矢量中的所有内容。 However, I cannot figure out how to format the each thing in a vector in a specific way: 但是,我无法弄清楚如何以特定的方式在矢量中格式化每件事:

record starts 0 spaces from left side 记录从左侧开始0个空格
fName starts 10 spaces from left side fName从左侧开始10个空格
lName starts right after a space that is after fName lName在fName之后的空格之后立即开始
phoneNum starts 30 spaces from left side phoneNum从左侧开始30个空格

all in 1 line. 全都在1行中。 Here is a picture example (can't format on this thread editor...) 这是一个图片示例(无法在此线程编辑器上格式化...)

http://i.imgur.com/bbAlDWX.png http://i.imgur.com/bbAlDWX.png

I understand this can be done using setw(), but thats only when you're directly outputting by using the << operators (or am I wrong?). 我知道可以使用setw()做到这一点,但这仅当您使用<<操作符直接输出时(否则我错了吗?)。 It needs to be in a form of a string so I can send it to the client through a socket. 它必须采用字符串形式,以便我可以通过套接字将其发送给客户端。

Does anyone know what I can do? 有人知道我能做什么吗?

#include <iomanip> and use all of its tools. #include <iomanip>并使用其所有工具。

You can build a string in the same way you'd output with cout if you #include <sstream> and use stringstreams 如果您#include <sstream>并使用stringstreams ,则可以使用与cout输出相同的方式来构建string

stringstream ss;
ss << //do stuff the same way you'd cout
return ss.str(); //or whatever you need to do with the built string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM