You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何通用解析多行字符串并赋值给不同类型变量?

通用解析多行输入为quantity、商品名与价格的C++实现

原场景与需求

原代码用于读取多行输入并拼接成字符串:

int main()
{
  int line=3, t;
  string s, bigString;

  for(int i=0 ; i<line ; i++)
  {
    getline(cin,s); 
    bigString += s + "\n";
  }
  cout <<bigString <<endl;
  return 0;
}

示例输入:

1 toy at 10.65
2 box of books at 12.11
1 pot plant at 6.45

需要将每行输入解析为:

  • int 类型的 quantity(每行开头的数字)
  • 商品名称(位于quantity和"at"之间的内容)
  • double 类型的价格("at"之后的数字)
    并将商品名与价格存入std::map<string, double>中。

通用解析方案

核心思路是利用字符串流和字符串定位,针对输入的固定特征(开头数字、中间商品名、"at"分隔价格)实现解析,同时处理格式异常:

#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    int lineCount = 3;
    string line;
    vector<pair<int, map<string, double>>> parsedResults;

    for (int i = 0; i < lineCount; ++i)
    {
        getline(cin, line);
        istringstream lineStream(line);
        
        // 读取开头的数量
        int quantity;
        if (!(lineStream >> quantity)) {
            cerr << "行格式错误:无法读取数量 - " << line << endl;
            continue;
        }

        // 获取数量之后的剩余字符串,跳过中间空格
        string remaining;
        getline(lineStream >> ws, remaining);

        // 定位分隔符" at "(前后带空格避免误匹配)
        size_t atSeparatorPos = remaining.find(" at ");
        if (atSeparatorPos == string::npos) {
            cerr << "行格式错误:未找到分隔符' at ' - " << line << endl;
            continue;
        }

        // 提取并清理商品名称
        string itemName = remaining.substr(0, atSeparatorPos);
        // 去除首尾空格
        itemName.erase(itemName.begin(), find_if(itemName.begin(), itemName.end(), [](int ch) {
            return !isspace(ch);
        }));
        itemName.erase(find_if(itemName.rbegin(), itemName.rend(), [](int ch) {
            return !isspace(ch);
        }).base(), itemName.end());

        // 提取并转换价格
        string priceStr = remaining.substr(atSeparatorPos + 4); // " at "共4个字符
        double price;
        istringstream priceStream(priceStr);
        if (!(priceStream >> price)) {
            cerr << "行格式错误:无法读取价格 - " << line << endl;
            continue;
        }

        // 存入结果结构
        map<string, double> itemMap;
        itemMap[itemName] = price;
        parsedResults.emplace_back(quantity, itemMap);

        // 验证输出
        cout << "当前行解析结果:" << endl;
        cout << "quantity = " << quantity << endl;
        cout << "商品名称:" << itemName << endl;
        cout << "价格:" << price << "\n" << endl;
    }

    return 0;
}

关键细节说明

  • 数量读取:通过istringstream直接读取开头整数,自动跳过前导空格
  • 分隔符定位:使用" at "(前后带空格)作为分隔符,避免商品名中包含"at"子串导致的误分割
  • 商品名清理:通过find_if去除首尾空格,确保名称格式整洁
  • 错误处理:对无法读取数量、找不到分隔符、价格格式错误的行输出提示,保证程序健壮性

内容的提问来源于stack exchange,提问作者Falcon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 20:39:19