如何读取带有空格的序列并在用户按C++中的"输入"时停止?
How to read sequences with spaces and stop when the user presses "enter" in C++?
作为标题,我是学习C 的初学者。
我想读取包含由空格分离到数组的整数的几个序列(S1,S2,S3 ...(,然后通过按" Enter"来读取S1以读取S2。
#
这是测试数据:
4 9 6 6
1 2 3 4
3 3 5 6 9 15 18 15 18 30 3 3 5 6 9 15 18 15 18 30 1 9 9 9 25 36
我期望的结果是:
arr [0] = {4,9,6,6}
arr [1] = {1,2,3,4}
arr [2] = {3,3,5,6,9,9,15,18,15,18,30,3,3,3,3,5,6,9,15,15,15,15,18,30,11,9,9,25,36}
#
我使用了一种耗时的方式将数据读取到我的数组中:
while(1){
int i=0,j=0;
int arr[100][25];
char test;
while(1){
stringstream ss;
cin.get(test);
if(test==' '){
ss<<seq;
seq.clear();
ss>>arr[i][j];
j++;
continue;
}
else if(test=='n'){
ss<<seq;
seq.clear();
ss>>arr[i][j];
i++;
j=0;
break;
}
else{
seq=seq+test;
}
}
}
在线法官将在程序读取大整数时显示" TLE"。
我知道将整数分解为角色是一项耗时的工作,
我该如何处理我的程序?
做到这一点的一种方法可能是使用字符串。下面的示例基于此答案,在字符串中读取每一行,然后按空格将其划分。仅当数字被单个空间拆分时,它才能起作用。拆分数字存储在示例中的字符串向量中,可以使用stoi
转换为int
。
string nums;
while(getline(cin,nums)) {
istringstream iss(nums);
vector<string> tokens;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(tokens));
// print what is added
for(int i = 0; i < tokens.size(); i++) {
cout << tokens[i] << " ";
}
cout << endl;
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- .cpp和.h文件中的模板专用化声明
- 反向给定链表中的K节点
- 正在查找文档以获得PS4平台的C++中的设备信息
- enum是C++中的宏变量还是整数变量
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 将字符串存储在c++中的稳定内存中
- 文本文件中的单词链表
- 递归函数计算序列中的平方和(并输出过程)
- 如何从C++中的依赖类型中获得它所依赖的类型
- C++中的"inline"关键字
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 用C++中的一个变量定义一个常量
- vector.resize()中的分配错误
- 使用指针从C++中的数组中获取最大值
- arr[-1]在c++中的奇怪行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 将值指定给向量(2D)的向量中的某个位置
- 内置函数可查看CPP中的成员变量