在c++中接受多个输入

Taking Multiple inputs in C++

本文关键字:输入 c++      更新时间:2023-10-16

我刚开始学习c++,有一个菜鸟问题。

假设我得到一个由空格分隔的输入,例如2 4 562 1 10 15hi bye ok。当输入的长度不知道时,我如何将值存储在数组中。

阅读std::vector

搜索空格并将每个空格中的字符串分割为如下

#include <iostream>
#include <string>
#include <vector>
using namespace std;

vector<string> GetInputs(string s)
{
    vector<size_t> foundSpacesPositions;
    vector<string> results;
    for (size_t i = 0; i < s.length(); i++)
    {
        if (isspace(s[i]))
        {
            foundSpacesPositions.push_back(i);
        }
    }
    size_t start = 0;
    for (size_t i = 0; i < foundSpacesPositions.size(); i++)
    {
        if (foundSpacesPositions[i] == start)
        {
            ++start;
            continue;
        }
        results.push_back(s.substr(start, foundSpacesPositions[i] - start));
        start = foundSpacesPositions[i] + 1;
    }
    if (start < s.length() - 1)
        results.push_back(s.substr(start, s.length() - 1));
    return results;
}
int _tmain(int argc, _TCHAR* argv[])
{
    string s = "a dd 8 ll ehh fd $%^ &   89 . ";
    vector<string> results = GetInputs(s);
    for (auto& res : results)
    {
        cout << res << endl;
    }
    cin.get();
    return 0;
}
/* OUTPUT
a
dd
8
ll
ehh
fd
$%^
&
89
.
*/

如果输入是字符串,您可以轻松地使用std::istringstream。如果输入是在stdin中给出的,则可以只使用std::cin流。std::istreamoperator<<将使用空格作为默认分隔符从字符串中获取整数。一旦您读取了流上的所有输入,std::istreamoperator bool将返回false,您可以停止读取。

一个示例实现是:

vector<int> getIntsFromString(const string& s) {
    istringstream ss(s);
    int i;
    vector<int> result;
    while (ss >> i) result.push_back(i);
    return move(result);
}

假设您从stdin中获得多行数量可变的整数,并且您希望将它们存储在vector<int>中。您可以做类似的事情:

string buf;
while (getline(cin, buf)) {
    auto v = getIntsFromString(buf);
    for (auto i : v) cout << i << ' ';
    cout << endl;
}