myStr = input("Enter something - ")
// say I enter "Hi there"
arrayStr = myStr.split()
print(arrayStr)
// Output: ['Hi', 'there']
这段代码的精确 C++ 等价物是什么? (我的目标是进一步迭代该数组并与其他数组进行比较)。
最佳答案
一种方法是使用 std::vector
和 std::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/