c++ - 如何在 C++ 中将输入字符串转换为数组?

标签 c++ arrays input

myStr = input("Enter something - ")

// say I enter "Hi there" 

arrayStr = myStr.split()
print(arrayStr)

// Output: ['Hi', 'there']

这段代码的精确 C++ 等价物是什么? (我的目标是进一步迭代该数组并与其他数组进行比较)。

最佳答案

一种方法是使用 std::vectorstd::istringstream ,如下所示:

#include <iostream>
#include <string>
#include<sstream>
#include <vector>
int main()
{
    std::string input, temp;
    //take input from user 
    std::getline(std::cin, input);
    
    //create a vector that will hold the individual words
    std::vector<std::string> vectorOfString;
    
    std::istringstream ss(input);
    
    //go word by word 
    while(ss >> temp)
    {
        vectorOfString.emplace_back(temp);
    }
    
    //iterate over all elements of the vector and print them out  
    for(const std::string& element: vectorOfString)
    {
        std::cout<<element<<std::endl;
    }
    return 0;
}

关于c++ - 如何在 C++ 中将输入字符串转换为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70665803/

相关文章:

c++ - 如何使用 CGAL 存储折叠的边缘

c++ - C++将十六进制字符串表示形式转换为十六进制

c - 问题查找字符串中给定子字符串的出现次数

c++ - 字符串和输入文件,从包含字符串的 txt 文件中分配几个变量值

c++ - 在 UMFPACK 中,我们需要多久进行一次符号和数值分解?

c++ - wxWidgets编译错误( fatal error LNK1120 : 26 unresolved externals)

arrays - 查找数组中所有元素实例的索引

C代码表现异常,特殊字符来自哪里?

符号的 Android 键码

javascript - Angular.js : ng-disabled based on sub-string in object array