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

如何分割输入字符串并转换类型存入指定并行数组?

分割输入并存入并行数组的实现方案

方案1:直接按空格分隔读取(最简单)

因为输入的三个字段天然用空格分隔,不需要先读成单个字符串再分割,直接用cin依次读取对应类型的变量,再完成检查和存入:

// 维护一个索引变量,跟踪当前要存入数组的位置(初始值设为0)
int currentIndex = 0;

double timeVal;
string lastName;
int playerNum;

// 自动按空格分割读取三个字段
cin >> timeVal >> lastName >> playerNum;

// 自定义检查逻辑(示例)
bool isValid = true;
if (timeVal < 0) { // 验证时间不能为负
    isValid = false;
}
if (playerNum <= 0) { // 验证球员编号为正整数
    isValid = false;
}
if (currentIndex >= size) { // 避免数组越界
    isValid = false;
}

// 检查通过后存入并行数组
if (isValid) {
    timeArray[currentIndex] = timeVal;
    lastnameArray[currentIndex] = lastName;
    playernumberArray[currentIndex] = playerNum;
    currentIndex++; // 索引自增,准备存下一组数据
}

方案2:先读取整行再分割(适配整行输入场景)

如果必须先把整行输入读成单个字符串再处理,可借助stringstream完成分割:

#include <sstream> // 必须包含该头文件

int currentIndex = 0;
string inputLine;

// 若之前用cin读过内容,需先清空换行符缓存(可选,根据实际输入流程调整)
// cin.ignore(numeric_limits<streamsize>::max(), '\n');

// 读取整行输入
getline(cin, inputLine);
stringstream inputStream(inputLine);

double timeVal;
string lastName;
int playerNum;

// 从流中按空格分割读取字段
inputStream >> timeVal >> lastName >> playerNum;

// 扩展检查:验证输入格式是否合法(比如球员编号是否为整数)
bool isValid = true;
if (inputStream.fail()) {
    isValid = false;
}
if (timeVal < 0 || playerNum <= 0) {
    isValid = false;
}
if (currentIndex >= size) {
    isValid = false;
}

// 存入数组
if (isValid) {
    timeArray[currentIndex] = timeVal;
    lastnameArray[currentIndex] = lastName;
    playernumberArray[currentIndex] = playerNum;
    currentIndex++;
}

核心注意事项

  • 必须严格维护数组索引,每次存入后自增,同时检查索引是否小于数组长度size,防止越界访问。
  • 检查逻辑可根据需求扩展,比如验证时间是否在合理范围、姓氏是否为空字符串等。
  • cin和stringstream会自动忽略多余的空格、制表符,无需额外处理格式问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:11:16