首页 > 解决方案 > 从字符串中解析名称和数字。将数字放入向量中

问题描述

给出的格式如下:

保罗 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;
    }
}

标签: c++parsingvector

解决方案


这是一个简单的第一次尝试的解决方案。如果您想要更高的性能/灵活性,您将不得不做更多的研究。
正如您所提到的,此解决方案要求输入字符串中的组件由空格分隔,以便能够产生正确的结果。

它使用std::istringstreamwhich 就像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.
为了能够解析名称包含空格的字符串,您将不得不更深入地研究并做更复杂的事情。


推荐阅读