完成split函数
EXAMPLE INPUT
123 abcde 567
ds tete dfsd 567
asd te sdfs 567
EXAMPLE OUTPUT
123
abcde
567
ds
tete
dfsd
567
asd
te
sdfs
567
主程序 (不能修改)
#include "source.cpp"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void test() {
string line;
getline(cin, line);
vector<string> words = split(line);
for (int i = 0; i < words.size(); ++ i) {
cout << words[i] << endl;
}
}
int main() {
test();
test();
test();
}
Mitte的答案
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
using namespace std;
vector<string> split(string line)
{
vector <string> word;
for(int i=0;i<line.length();i++)
{
char t[20];
memset(t,0,sizeof(t));
for(int j=i;j<line.length();j++)
{
if(line[j]==' ')
{
i=j;
break;
}
t[j-i]=line[j];
}
word.push_back(t);
}
return word;
}
我的答案
#include<vector>
#include <cstring>
#include<iostream>
using namespace std;
vector<string> split(string str)
{
vector <string> word;
const char * s=" ";
int n = 0;
char *token;
token = strtok(str, s);
while(token!= NULL)
{
word[n++]=token;
token=strtok(NULL,s);
}
return word;
}
报错信息
In file included from main.cpp:1:0:
source.cpp: In function ‘std::vector<std::__cxx11::basic_string<char> > split(std::__cxx11::string)’:
source.cpp:11:25: error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘char*’ for argument ‘1’ to ‘char* strtok(char*, const char*)’
token = strtok(str, s);