C ++问题:
我在txt中有这样的查询:
CUSTOMER_ID=4155&ORDER_ITEM_TYPE_ID=1&ORDER_ITEM_TYPE_NAME=Product&ORDER_ITEM_SKU=&ORDER_CURRENCY_CODE=UAH
如何让这些字段看起来像:
Customer_ID: 4155
ORDER_ITEM_TYPE_ID: 1
// and etc...
我知道有一个分隔符“&”在每个领域之间,但我不知道如何正确地做到这一点。
答案 0 :(得分:0)
试
`char str[10][20];
int len = 0;
int count = 0;
while((c = string[i])!= EOC )
/* EOC : End of Character */
{
if (c == '&') {
str[count][len] = '\0';
len = 0;
count++;
continue;
}
str[count][len] = c;
len++;
}
答案 1 :(得分:0)
使用std::string
的方法,例如find
,substr
。例如:
const std::string field = "CUSTOMER_ID=4155&ORDER_ITEM_TYPE_ID=1&ORDER_ITEM_TYPE_NAME=Product&ORDER_ITEM_SKU=&ORDER_CURRENCY_CODE=UAH";
const char separator = '&';
const char equal = '=';
std::string::size_type cur = 0;
while ( cur != std::string::npos )
{
std::string name;
std::string value;
std::string::size_type newPos = field.find(equal, cur);
if ( newPos != std::string::npos )
{
name = field.substr( cur, newPos - cur );
cur = newPos + 1;
newPos = field.find(separator, cur);
value = field.substr( cur, ( newPos == std::string::npos ) ? std::string::npos : newPos - cur );
cur = ( newPos == std::string::npos ) ? std::string::npos : newPos + 1;
std::cout << name << ": " << value << std::endl;
}
else
{
break;
}
}
答案 2 :(得分:0)
替换所有'&amp;'使用替换,然后当您将数据写回文件后,它将根据请求进行格式化。
std::ifstream infile("thefile.txt");
while (std::getline(infile, line)) //Read File line by line
{
std::replace( line.begin(), line.end(), '&', '\0'); // replace all '&' to '\0'
cout << line << endl;
}