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

C++如何读取D-C0-1234-5格式字符串并提取中间数字参与运算

解决方案

你可以直接使用scanf函数的格式化匹配能力处理该场景,无需手动拆分字符串,修改成本极低:
scanf支持通过格式串指定跳过固定分隔符和非目标内容,针对D-C0-1234-5这类[段1]-[段2]-[目标数字段]-[段4]的固定格式,直接使用格式串%*[^-]-%*[^-]-%lf-%*s即可直接提取第三段的数字存入变量L:

  • %*[^-]:匹配所有非-的字符,*表示匹配到的内容直接丢弃不存储
  • 紧随的-:匹配分隔符并丢弃
  • 重复两次上述规则后,就定位到了第三段目标数字,用%lf读取数字存入L
  • 末尾的-%*s:匹配剩余的分隔符和最后一段内容并丢弃

修改后的完整代码

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    double a = 11.7 * pow(10, -6);
    double L;
    double increase_length, total_length;
    int temp_difference = 0;

    cout << "My student number is : "; 
    // 替换原来的cin >> L,直接用scanf按格式提取数字
    scanf("%*[^-]-%*[^-]-%lf-%*s", &L);

    cout << endl << "Initial Length : " << L << " meters" << endl << endl;

    printf("%26s%17s\n", "Length", "Total");
    printf("%s%16s%17s\n", "Temperature", "Increase", "Length");
    printf("%10s%19s%17s\n", "(Celsius)", "(in meters)", "(in meters)");
    printf("%10s%18s%17s\n", "-----------", "-----------", "-----------");

    while(temp_difference <= 50)
    {
        increase_length = a * L * temp_difference;
        total_length = L + increase_length;

        printf("%7d%20.4f%18.4f\n", temp_difference, increase_length, total_length);

        temp_difference = temp_difference + 5;
    }

    return 0;
}

如果你需要先存储完整的输入字符串再做处理,也可以先把整行读入std::string对象,再用find方法定位-的位置,用substr截取第三段后转成double类型即可,适合格式不固定的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:27:04