c++ - 从字符串中解析名称和数字。将数字放入向量中
问题描述
给出的格式如下:
保罗 34 56 72 89 92
我想读取名称并将数字放入/解析为 int 矢量标记。上述格式中的所有内容都由空格分隔。
这是我解决这个问题的尝试。有一个错字...排名实际上是标记
StudentEntry:: StudentEntry(string line) {
int temp = line.find(' '); // end of the name
name = line.substr(0, temp);
string numbers = line.substr(temp+1);
for (int i=0; i<rank.size(); i++) {
rank.push_back(i);
cout << "RANK: " << rank[i] <<endl;
}
}
解决方案
这是一个简单的第一次尝试的解决方案。如果您想要更高的性能/灵活性,您将不得不做更多的研究。
正如您所提到的,此解决方案要求输入字符串中的组件由空格分隔,以便能够产生正确的结果。
它使用std::istringstream
which 就像std::cin
. 您向它提供输入字符串并继续从中读取以空格分隔的组件。
#include <vector>
#include <string>
#include <sstream>
std::istringstream iss{ line }; // initialize with the input string
std::string name;
iss >> name; // extract the first component as a string
std::vector<int> marks;
for (int num = 0; iss >> num;) // extract rest of the components as int
marks.push_back(num); // and store them in a vector
请记住,名称不能包含空格。
例如,此解决方案不适用于此输入:Paul Walker 34 56 72 89 92
.
为了能够解析名称包含空格的字符串,您将不得不更深入地研究并做更复杂的事情。
推荐阅读
- java - 包含依赖项的简单 OSGi 应用程序
- jquery - Cheerio 集合元素没有 innerHTML 属性
- axios - 反应 axios 不提供响应
- kubernetes - Kubernetes:kubeadm init - CGROUPS_PIDS:缺失
- junit5 - Junit5 - ParallelExecutionConfigurationStrategy - 如何?
- python - 通过 pip 安装 PySCIPOpt 不起作用
- opencv - Opencv没有安装?
- clickhouse - Clickhouse 中的 UInt64 与字符串?
- php - 在 HTML 字符串之间使用 Wordpress do_shortcode 时出现语法错误
- javascript - babel 重命名的函数参数与 jsdoc 不匹配