如果我输入kampret,如何将其声明为变量,示例ALEX是名称变量,19是旧变量,INDIA是国家变量。用我的程序
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char str[100];
cout<<"Enter string : ";cin>>str;
char *point;
point=strjum(str, "#");
while(point!=NULL){
cout<<point<<endl;
point = surtok(NULL, "#");
}
}
答案 0 :(得分:0)
你应该使用std:string及其方法,但是如果你必须使用strtok:
char *name;
char * age;
char * country;
point=strtok(str, "#");
if(point != NULL)
{
name = strdup(point);
point = strtok(NULL, "#");
if(point != NULL)
{
age = strdup(point);
point = strtok(NULL, "#");
if(point != NULL)
{
country = strdup(point);
}
}
}
答案 1 :(得分:0)
std::string
比克里斯提到的评论方法更安全。
为了您的学习:
#include <iostream>
#include <string>
int main() {
std::string s = "ALEX#19#INDIA";
std::string delimiter = "#";
size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;
return 0;
}
如果我需要代码
,我会怎么做#include <string>
#include <vector>
#include <functional>
#include <iostream>
void split(const std::string& s, char c,
std::vector<std::string>& v) {
std::string::size_type i = 0;
std::string::size_type j = s.find(c);
while (j != std::string::npos) {
v.push_back(s.substr(i, j-i));
i = ++j;
j = s.find(c, j);
if (j == std::string::npos)
v.push_back(s.substr(i, s.length()));
}
}
int main() {
std::vector<std::string> v;
std::string s = "ALEX#19#INDIA";
char delimiter = '#';
split(s, delimiter, v);
for (auto& i : v) {
std::cout << i << '\n';
}
}