C语言中未知输入数量时如何从同一行读取多个输入?
不定长度时间字符串输入读取实现方案
核心逻辑
无需提前预知输入元素个数,直接读取完整一行输入内容,按空白字符分割后过滤空值即可得到所有时间项,同时可以增加输入长度校验适配4~10000字符的要求。
各语言实现示例
Python
- 直接使用内置
input()读取整行,split()方法自动按任意空白分割、过滤空值,代码最简。
# 读取整行输入 input_str = input().strip() # 校验输入长度 if not (4 <= len(input_str) <= 10000): raise ValueError("输入长度不符合要求") # 分割得到时间列表 time_list = input_str.split()
Java
- 使用
BufferedReader读取长输入性能更优,避免Scanner的额外解析开销。
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.util.List; public class TimeInputReader { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = br.readLine().trim(); // 校验输入长度 if (input.length() < 4 || input.length() > 10000) { throw new IllegalArgumentException("输入长度不合法"); } // 按任意空白分割得到时间列表 List<String> timeList = Arrays.asList(input.split("\\s+")); } }
C++
- 用
getline读取整行避免cin默认空格截断的问题,用字符串流分割内容。
#include <iostream> #include <string> #include <vector> #include <sstream> #include <stdexcept> int main() { std::string input; std::getline(std::cin, input); // 校验输入长度 if (input.size() < 4 || input.size() > 10000) { throw std::invalid_argument("输入长度不合法"); } std::vector<std::string> time_list; std::stringstream ss(input); std::string time_item; while (ss >> time_item) { time_list.push_back(time_item); } return 0; }
补充说明
- 若实际场景使用非空白分隔符(如逗号、分号),只需替换分割规则的匹配逻辑即可。
- 读取完成后可自行添加格式校验逻辑,验证每个元素是否符合
HH:MM的时间格式要求。
内容的提问来源于stack exchange,提问作者sivaram
相关产品推荐
相关产品推荐

