txp*_*030 19 c++ arrays string vector
我试图插入一个由空格分隔的字符串到一个字符串数组,而不使用C++中的vector.例如:
using namespace std;
int main() {
string line = "test one two three.";
string arr[4];
//codes here to put each word in string line into string array arr
for(int i = 0; i < 4; i++) {
cout << arr[i] << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望输出为:
test
one
two
three.
Run Code Online (Sandbox Code Playgroud)
我知道在C++中已经有很多问题要求字符串>数组.我意识到这可能是一个重复的问题,但我找不到任何满足我条件的答案(将字符串拆分为数组而不使用向量).如果这是一个重复的问题,我会提前道歉.
did*_*erc 39
可以通过使用std::stringstream
类将其转换为流(其构造函数将字符串作为参数).一旦构建完成,就可以>>
在其上使用运算符(比如基于常规文件的流),它将从中提取或标记单词:
#include <iostream>
#include <sstream>
using namespace std;
int main(){
string line = "test one two three.";
string arr[4];
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 4){
ssin >> arr[i];
++i;
}
for(i = 0; i < 4; i++){
cout << arr[i] << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
#include <iostream>
#include <sstream>
#include <iterator>
#include <string>
using namespace std;
template <size_t N>
void splitString(string (&arr)[N], string str)
{
int n = 0;
istringstream iss(str);
for (auto it = istream_iterator<string>(iss); it != istream_iterator<string>() && n < N; ++it, ++n)
arr[n] = *it;
}
int main()
{
string line = "test one two three.";
string arr[4];
splitString(arr, line);
for (int i = 0; i < 4; i++)
cout << arr[i] << endl;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
134251 次 |
最近记录: |