-3

if I input kampret, how to declarate it into a variable, examples ALEX is a name variable , 19 is old variable , and INDIA is country variable. with my program

#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, "#");
}
}
  • What is "variable"? Names of variables declared in C++ code won't be available except for in debugging information. – MikeCAT Jun 01 '16 at 17:12
  • 3
    You can refer to [this answer](http://stackoverflow.com/a/236803/962089) to split a string. A `std::string` will certainly be safer than your current, easy-to-attack input method. Once you split the string, accessing the pieces to store them in separate variables is much easier. – chris Jun 01 '16 at 17:14
  • More info why not to use `strtok()` [here](http://stackoverflow.com/questions/2799023/what-exactly-is-a-reentrant-function/2799288#2799288). – πάντα ῥεῖ Jun 01 '16 at 17:15
  • 1
    http://www.cplusplus.com/faq/sequences/strings/split/ – Leonardo Alves Machado Jun 01 '16 at 17:15

2 Answers2

0

you should really use std:string and its methods, but if you must use 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);
    }
  }
}
pm100
  • 48,078
  • 23
  • 82
  • 145
0

std::string is more safer than your method like chris mentioned as a comment. For your learning:

#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;
}

What I do if I need like the code

#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';
    }
}