Search Results

Search found 76 results on 4 pages for 'strtok'.

Page 1/4 | 1 2 3 4  | Next Page >

  • Trying to understand strtok

    - by Karthick
    Consider the following snippet that uses strtok to split the string madddy. char* str = (char*) malloc(sizeof("Madddy")); strcpy(str,"Madddy"); char* tmp = strtok(str,"d"); std::cout<<tmp; do { std::cout<<tmp; tmp=strtok(NULL, "dddy"); }while(tmp!=NULL); It works fine, the output is Ma. But by modifying the strtok to the following, tmp=strtok(NULL, "ay"); The output becomes Madd. So how does strtok exactly work? I have this question because I expected strtok to take each and every character that is in the delimiter string to be taken as a delimiter. But in certain cases it is doing that way but in few cases, it is giving unexpected results. Could anyone help me understand this?

    Read the article

  • strtok problem in calling

    - by Moony
    I have a function using strtok like this void f1(char *name) { ... char *tmp; tmp = strtok(names, " ,"); while(tmp) { ... tmp = strtok(NULL, " ,"); } ... } And i have a call f1("abc,def"); Problem is that in first call f1 gets abc,def and in 2nd call gets just abc I am confused.. Why is this so?

    Read the article

  • strtok wont accept: char *str

    - by bks
    strtok wont work correctly when using char *str as the first parameter (not the delimiters string). does it have something to do with the area that allocates strings in that notation? (which as far as i know, is a read-only area). thanks in advance example: //char* str ="- This, a sample string."; // <---doesn't work char str[] ="- This, a sample string."; // <---works char delims[] = " "; char * pch; printf ("Splitting string \"%s\" into tokens:\n",str); pch = strtok (str,delims); while (pch != NULL) { printf ("%s\n",pch); pch = strtok (NULL, delims); } return 0;

    Read the article

  • Copy results of strtok to 2 strings in C

    - by Mr. Man
    Ok, so I have the code char *token; char *delimiter = " "; token = strtok(command, delimiter); strcpy(command, token); token = strtok(NULL, delimiter); strcpy(arguments, token); and it gives me EXC_BAD_ACCESS when i run it, and yes, command and arguments are already defined.

    Read the article

  • Structs, strtok, segmentation fault

    - by FILIaS
    I'm trying to make a programme with structs and files.The following is just a part of my code(it;s not all). What i'm trying to do is: ask the user to write his command. eg. delete John eg. enter John James 5000 ipad purchase. The problem is that I want to split the command in order to save its 'args' for a struct element. That's why i used strtok. BUT I'm facing another problem in who to 'put' these on the struct. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 100 char command[1500]; struct catalogue { char short_name[50]; char surname[50]; signed int amount; char description[1000]; }*catalog[MAX]; int main ( int argc, char *argv[] ) { int i,n; char choice[3]; printf(">sort1: Print savings sorted by surname\n"); printf(">sort2: Print savings sorted by amount\n"); printf(">search+name:Print savings of each name searched\n"); printf(">delete+full_name+amount: Erase saving\n"); printf(">enter+full_name+amount+description: Enter saving \n"); printf(">quit: Update + EXIT program.\n"); printf("Choose your selection:\n>"); gets(command); //it save the whole command /*in choice it;s saved only the first 2 letters(needed for menu choice again)*/ strncpy(choice,command,2); choice[2]='\0'; char** args = (char**)malloc(strlen(command)*sizeof(char*)); memset(args, 0, sizeof(char*)*strlen(command)); char* curToken = strtok(command, " \t"); for (n = 0; curToken != NULL; ++n) { args[n] = strdup(curToken); curToken = strtok(NULL, " \t"); *catalog[n]->short_name=*args[1]; *catalog[n]->surname=args[2]; catalog[n]->amount=atoi(args[3]); *catalog[n]->description=args[4]; } return 0; } I get a warning (warning: assignment makes integer from pointer without a cast) for the lines: *catalog[n]->short_name=*args[1]; *catalog[n]->surname=args[2]; *catalog[n]->description=args[4]; As a result, after running the program i get a Segmentation Fault... Any help? Any ideas?

    Read the article

  • valgrind complains doing a very simple strtok in c

    - by monkeyking
    Hi I'm trying to tokenize a string by loading an entire file into a char[] using fread. For some strange reason it is not always working, and valgrind complains in this very small sample program. Given an input like test.txt first second And the following program #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/stat.h> //returns the filesize in bytes size_t fsize(const char* fname){ struct stat st ; stat(fname,&st); return st.st_size; } int main(int argc, char *argv[]){ FILE *fp = NULL; if(NULL==(fp=fopen(argv[1],"r"))){ fprintf(stderr,"\t-> Error reading file:%s\n",argv[1]); return 0; } char buffer[fsize(argv[1])]; fread(buffer,sizeof(char),fsize(argv[1]),fp); char *str = strtok(buffer," \t\n"); while(NULL!=str){ fprintf(stderr,"token is:%s with strlen:%lu\n",str,strlen(str)); str = strtok(NULL," \t\n"); } return 0; } compiling like gcc test.c -std=c99 -ggdb running like ./a.out test.txt thanks

    Read the article

  • How to use strtok in C properly so there is no memory leak?

    - by user246392
    I am somewhat confused by what happens when you call strtok on a char pointer in C. I know that it modifies the contents of the string, so if I call strtok on a variable named 'line', its content will change. Assume I follow the bellow approach: void function myFunc(char* line) { // get a pointer to the original memory block char* garbageLine = line; // Do some work // Call strtok on 'line' multiple times until it returns NULL // Do more work free(garbageLine); } Further assume that 'line' is malloced before it is passed to myFunc. Am I supposed to free the original string after using strtok or does it do the job for us? Also, what happens if 'line' is not malloced and I attempt to use the function above? Is it safer to do the following instead? (Assume the programmer won't call free if he knows the line is not malloced) Invocation char* garbageLine = line; myFunc(line); free(garbageLine); Function definition void function myFunc(char* line) { // Do some work // Call strtok on 'line' multiple times until it returns NULL // Do more work }

    Read the article

  • Using strtok() in a loop in C?

    - by Alex Xander
    I am trying to use strtok() in nested loop. But this is not giving me desired results. Possibly because they are using same memory location. My code is of the form:- char *token1 = strtok(Str1, "%"); while(token1 != NULL ) { char *token2 = strtok(Str2, "%"); while(token2 != NULL ) { //DO SMTHING token2 = strtok(NULL, "%"); } token1 = strtok(NULL, "%"); // Do something more }

    Read the article

  • char array split ip with strtok

    - by user1480139
    I'm trying to split a IP address like 127.0.0.1 from a file: using following C code: pch2 = strtok (ip,"."); printf("\npart 1 ip: %s",pch2); pch2 = strtok (NULL,"."); printf("\npart 2 ip: %s",pch2); And IP is a char ip[500], that containt an ip. When printing it prints 127 as part 1 but as part 2 it prints NULL? Can someone help me? EDIT: Whole function: FILE *file = fopen ("host.txt", "r"); char * pch; char * pch2; char ip[BUFFSIZE]; IPPart result; if (file != NULL) { char line [BUFFSIZE]; while(fgets(line,sizeof line,file) != NULL) { if(line[0] != '#') { //fputs(line,stdout); pch = strtok (line," "); printf ("%s\n",pch); strncpy(ip, pch, sizeof(pch)-1); ip[sizeof(pch)-1] = '\0'; //pch = strtok (line, " "); pch = strtok (NULL," "); printf("%s",pch); pch2 = strtok (ip,"."); printf("\nDeel 1 ip: %s",pch2); pch2 = strtok (NULL,"."); printf("\nDeel 2 ip: %s",pch2); //if(strcmp(pch,url) == 0) //{ // result.part1 = //} } } fclose(file); }

    Read the article

  • strtok program crashing.

    - by baskin
    Hi, the program for strtok given on http://www.opengroup.org/onlinepubs/000095399/functions/strtok.html crashes everytime.. #include <string.h> ... char *token; char *line = "LINE TO BE SEPARATED"; char *search = " "; /* Token will point to "LINE". */ token = strtok(line, search); /* Token will point to "TO". */ token = strtok(NULL, search); If I use a char array for variable 'line', it works. i.e. char line[] = "LINE TO BE SEPARATED" works. Kindly explain.

    Read the article

  • How to make the tokenizer detect empty spaces while using strtok()

    - by Shadi Al Mahallawy
    I am designing a c++ program, somewhere in the program i need to detect if there is a blank(empty token) next to the token used know eg. if(token1==start) { token2=strtok(NULL," "); if(token2==NULL) {LCCTR=0;} else {LCCTR=atoi(token2);} so in the previous peice token1 is pointing to start , and i want to check if there is anumber next to the start , so I used token2=strtok(NULL," ") to point to the next token but unfortunattly the strtok function cannot detect empty spaces so it gives me an error at run time"INVALID NULL POINTER" how can i fix it or is there another function to use to detect empty spaces #include <iostream> #include<string> #include<map> #include<iomanip> #include<fstream> #include<ctype.h> using namespace std; const int MAX=300; int LCCTR; int START(char* token1); char* PASS1(char*token1); void tokinizer() { ifstream in; ofstream out; char oneline[MAX]; in.open("infile.txt"); out.open("outfile.txt"); if(in.is_open()) { char *token1; in.getline(oneline,MAX); token1 = strtok(oneline," \t"); START (token1); //cout<<'\t'; while(token1!=NULL) { //PASS1(token1); //cout<<token1<<" "; token1=strtok(NULL," \t"); if(NULL==token1) {//cout<<endl; //cout<<LCCTR<<'\t'; in.getline(oneline,MAX); token1 = strtok(oneline," \t"); } } } in.close(); out.close(); } int START(char* token1) { string start("START"); char*token2; if(token1 != start) {LCCTR=0;} else if(token1==start) { token2=strchr(token1+2,' '); cout<<token2; if(token2==NULL) {LCCTR=0;} else {LCCTR=atoi(token2); if(atoi(token2)>9999||atoi(token2)<0){cout<<"IVALID STARTING ADDRESS"<<endl;exit(1);} } } return LCCTR; } char* PASS1 (char*token1) { map<string,int> operations; map<string,int>symtable; map<string,int>::iterator it; pair<map<string,int>::iterator,bool> ret; char*token3=NULL; char*token2=NULL; string test; string comp(" "); string start("START"); string word("WORD"); string byte("BYTE"); string resb("RESB"); string resw("RESW"); string end("END"); operations["ADD"] = 18; operations["AND"] = 40; operations["COMP"] = 28; operations["DIV"] = 24; operations["J"] = 0X3c; operations["JEQ"] =30; operations["JGT"] =34; operations["JLT"] =38; operations["JSUB"] =48; operations["LDA"] =00; operations["LDCH"] =50; operations["LDL"] =55; operations["LDX"] =04; operations["MUL"] =20; operations["OR"] =44; operations["RD"] =0xd8; operations["RSUB"] =0x4c; operations["STA"] =0x0c; operations["STCH"] =54; operations["STL"] =14; operations["STSW"] =0xe8; operations["STX"] =10; operations["SUB"] =0x1c; operations["TD"] =0xe0; operations["TIX"] =0x2c; operations["WD"] =0xdc; if(operations.find("ADD")->first==token1) { token2=strtok(NULL," "); //test=token2; cout<<token2; //if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} //else{LCCTR=LCCTR+3;} } /*else if(operations.find("AND")->first==token1) { token2=strtok(NULL," "); test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("COMP")->first==token1) { token2=token1+5; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("DIV")->first==token1) { token2=token1+4; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("J")->first==token1) { token2=token1+2; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("JEQ")->first==token1) { token2=token1+5; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("JGT")->first==token1) { token2=strtok(NULL," "); test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("JLT")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("JSUB")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("LDA")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("LDCH")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("LDL")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("LDX")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("MUL")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("OR")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("RD")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("RSUB")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("STA")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("STCH")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("STL")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("STSW")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("STX")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("SUB")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("TD")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("TIX")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} } else if(operations.find("WD")->first==token1) { token2=token1+6; test=token2; if(test.empty()){cout<<"MISSING OPERAND"<<endl;exit(1);} else{LCCTR=LCCTR+3;} }*/ //else if( if(word==token1) {LCCTR=LCCTR+3;} else if(byte==token1) {string test; token2=token1+7; test=token2; if(test[0]=='C') {token3=token1+10; test=token3; if(test.length()>15) {cout<<"ERROR"<<endl; exit(1);} } else if(test[0]=='X') {token3=token1+10; test=token3; if(test.length()>14) {cout<<"ERROR"<<endl; exit(1);} } LCCTR=LCCTR+test.length(); } else if(resb==token1) {token3=token1+5; LCCTR=LCCTR+atoi(token3);} else if(resw==token1) {token3=token1+5; LCCTR=LCCTR+3*atoi(token3);} else if(end==token1) {exit(1);} /*else { test=token1; int last=test.length(); if(token1==start||test[0]=='C'||test[0]=='X'||ispunct(test[last])||isdigit(test[0])||isdigit(test[1])||isdigit(test[2])||isdigit(test[3])){} else { token2=strtok(NULL," "); //test=token2; cout<<token2; if(token2!=NULL) { symtable.insert( pair<string,int>(token1,LCCTR)); for(it=symtable.begin() ;it!=symtable.end() ;++it) {/*cout<<"symbol: "<<it->first<<" LCCTR: "<<it->second<<endl;} } else{} } }*/ return token3; } int main() { tokinizer(); return 0; }

    Read the article

  • Redirecting one file to another using dub2 and strtok

    - by Sergiy Zakharov
    OK, here goes. I have to write a program, in which I need to use strtok and dup2 to redirect one file to another, but I need to also have the user to actually put the command cat < file1 file2, but not from the shell, but instead by using my program. That's why I need strtok. And the reason my program doesn't work is probably because of that, because I don't really understand how strtok works. I found a similar program on the internet, but they just take the ls command and redirect it to the file. That's it. My program is much more complicated. I mean, it would've been easier just to say in shell cat < file1 file2, but for some reason they want us to do it this way. So, anyways, here is what I have so far (here I just combined what I have found on the internet with what I already had from before. We had to do something similar but then the user would just go ls or ls -l. Very simple stuff. This is much harder, for me, at least.) #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <sys/wait.h> #include <string.h> int main() { pid_t pid; char line[256]; char *args[129]; int i; int fd; int status; char *temp; while (1) { printf(">"); if (fgets(line, 256, stdin) == 0) { exit(0); } else { pid = fork(); if (pid == 0) { i = 0; temp = strtok("<",line); while (temp != NULL) { args[i++] = temp; temp = strtok(">",line); args[i] = '\0'; } fd = open("hello", O_RDONLY); dup2(fd, STDIN_FILENO); fd = open("world", O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU); dup2(fd, STDOUT_FILENO ); close(fd); execvp(args[0], args); } else { close(fd); wait(&status); } } } } Any help would be greatly appreciated.

    Read the article

  • C - array count, strtok, etc

    - by Pedro
    Hi... i have a little problem on my code... HI open a txt that have this: LEI;7671;Maria Albertina da silva;[email protected]; 9;8;12;9;12;11;6;15;7;11; LTCGM;6567;Artur Pereira Ribeiro;[email protected]; 6;13;14;12;11;16;14; LEI;7701;Ana Maria Carvalho;[email protected]; 8;13;11;7;14;12;11;16;14; LEI, LTCGM are the college; 7671, 6567, 7701 is student number; Maria, Artur e Ana are the students name; [email protected], ...@gmail are emails from students; the first number of every line is the total of classes that students have; after that is students school notes; example: College: LEI Number: 7671 Name: Maria Albertina da Silva email: [email protected] total of classes: 9 Classe Notes: 8 12 9 12 11 6 15 7 11. My code: typedef struct aluno{ char sigla[5];//college char numero[80];//number char nome[80];//student name char email[20];//email int total_notas;// total of classes char tot_not[40]; // total classes char notas[20];// classe notes int nota; //class notes char situacao[80]; //situation (aproved or disaproved) }ALUNO; void ordena(ALUNO*alunos, int tam)//bubble sort { int i=0; int j=0; char temp[100]; for( i=0;i<tam;i++) for(j=0;j<tam-1;j++) if(strcmp( alunos[i].sigla[j], alunos[i].sigla[j+1])>0){ strcpy(temp, alunos[i].sigla[j]); strcpy(alunos[i].sigla[j],alunos[i].sigla[j+1]); strcpy(alunos[i].sigla[j+1], temp); } } void xml(ALUNO*alunos, int tam){ FILE *fp; char linha[60];//line int soma, max, min, count;//biggest note and lowest note and students per course count float media; //media of notes fp=fopen("example.txt","r"); if(fp==NULL){ exit(1); } else{ while(!(feof(fp))){ soma=0; media=0; max=0; min=0; count=0; fgets(linha,60,fp); if(linha[0]=='L'){ if(ap_dados=strtok(linha,";")){ strcpy(alunos[i].sigla,ap_dados);//copy to struct // i need to call bubble sort here, but i don't know how printf("College: %s\n",alunos[i].sigla); if(ap_dados=strtok(NULL,";")){ strcpy(alunos[i].numero,ap_dados);//copy to struct printf("number: %s\n",alunos[i].numero); if(ap_dados=strtok(NULL,";")){ strcpy(alunos[i].nome, ap_dados);//copy to struct printf("name: %s\n",alunos[i].nome); if(ap_dados=strtok(NULL,";")){ strcpy(alunos[i].email, ap_dados);//copy to struct printf("email: %s\n",alunos[i].email); } } } }i++; } if(isdigit(linha[0])){ if(info_notas=strtok(linha,";")){ strcpy(alunos[i].tot_not,info_notas); alunos[i].total_notas=atoi(alunos[i].tot_not);//total classes for(z=0;z<=alunos[i].total_notas;z++){ if(info_notas=strtok(NULL,";")){ strcpy(alunos[i].notas,info_notas); alunos[i].nota=atoi(alunos[i].notas); // student class notes } soma=soma + alunos[i].nota; media=soma/alunos[i].total_notas;//doesn't work if(alunos[i].nota>max){ max=alunos[i].nota;;//doesn't work } else{ if(min<alunos[i].nota){ min=alunos[i].nota;;//doesn't work } } //now i need to count the numbers of students in the same college, but doesn't work /*If(strcmp(alunos[i].sigla, alunos[i+1].sigla)=0){ count ++; printf("%d\n", count); here for LEI should appear 2 students and for LTCGM appear 1, don't work }*/ //Now i need to see if student is aproved or disaproved // Student is disaproved if he gets 3 notes under 10, how can i do that? } printf("media %d\n",media); //media printf("Nota maxima %d\n",max);// biggest note printf("Nota minima %d\n",min); //lowest note }i++; } } } fclose(fp); } int main(int argc, char *argv[]){ ALUNO alunos; FILE *fp; int tam; fp=fopen(nomeFicheiro,"r"); alunos = (ALUNO*) calloc (tam, sizeof(ALUNO)); xml(alunos,nomeFicheiro, tam); system("PAUSE"); return 0; }

    Read the article

  • parsing string off a configuration using strtok in C

    - by Jessica
    in the configuration file i have entries similar to this one: filepath = c:\Program Files\some value Where the path can contain spaces and there are no quotes on that string. I tried parsing this with strtok like: char *option; char *value; value = strtok(line, " ="); strcpy(option, value); value = strtok(NULL, " ="); where line is the line I am reading from the file, option will contain the left side of the equal (filepath) and value will contain the right side (c:\program files\some value). I know, it's poor coding, but I haven't found something better. sorry... In any case, for those options where there's no space in the right side it works great, but in those containing spaces it only return the string until the 1st space: c:\Program. Is there any other way to do this? Code is appreciated. Jessica

    Read the article

  • PHP String tokenizer not working correctly

    - by asdadas
    I have no clue why strtok decided to break on me. Here is my code. I am tokenizing a string by dollar symbol $. echo 'Tokenizing this by $: ',$aliases,PHP_EOL; if(strlen($aliases) > 0) { //aliases check $token = strtok($aliases, '$'); while($token != NULL) { echo 'Found a token: ',$token,PHP_EOL; if(!isGoodLookup($token)) { echo 'ERROR: Invalid alias found.',PHP_EOL; stop($db); } $goodAliasesList[] = $token; $token = strtok('$'); } if($token == NULL) echo 'Found null token, moving on',PHP_EOL; } And this is my output: Tokenizing this by $: getaways$aaa Found a token: getaways Found null token, moving on str tok is not supposed to do this!! where is my aaa token!!

    Read the article

  • Strange things appear on running the program

    - by FILIaS
    Hey! I'm fixing a program but I'm facing a problem and I cant really realize what's the wrong on the code. I would appreciate any help. I didnt post all the code...but i think with this part you can get an idea of it. With the following function enter() I wanna add user commands' datas to a list. eg. user give the command: "enter james bond 007 gun" 'james' is supposed to be the name, 'bond' the surname, 007 the amount and the rest is the description. I use strtok in order to 'cut' the command,then i put each name on a temp array. Then i call InsertSort in order to put the datas on a linked list but in alphabetical order depending on the surname that users give. I wanna keep the list on order and put each time the elements on the right position. /* struct for all the datas that user enters on file*/ typedef struct catalog { char short_name[50]; char surname[50]; signed int amount; char description[1000]; struct catalog *next; }catalog,*catalogPointer; catalogPointer current; catalogPointer head = NULL; void enter(void)//user command: enter <name> <surname> <amount> <description> { int n,j=2,k=0; char temp[1500]; char command[1500]; while (command[j]!=' ' && command[j]!='\0') { temp[k]=command[j]; j++; k++; } temp[k]='\0'; char *curToken = strtok(temp," "); printf("temp is:%s \n",temp); char short_name[50],surname[50],description[1000]; signed int amount; //short_name=(char *)malloc(sizeof (char *)); //surname=(char *)malloc(sizeof (char *)); //description=(char *)malloc(sizeof (char *)); //amount=(int *)malloc(sizeof (int *)); printf("\nWhat you entered for saving:\n"); for (n = 0; curToken !='\0'; ++n) { if (curToken) { strncpy(short_name, curToken, sizeof (char *)); / } printf("Short Name: %s \n",short_name); curToken = strtok(NULL," "); if (curToken) strncpy(surname, curToken, sizeof (char *)); / printf("SurName: %s \n",surname); curToken = strtok(NULL," "); if (curToken) { char *chk; amount = (int) strtol(curToken, &chk, 10); if (!isspace(*chk) && *chk != 0) fprintf(stderr,"Warning: expected integer value for amount, received %s instead\n",curToken); } printf("Amount: %d \n",amount); curToken = strtok(NULL,"\0"); if (curToken) { strncpy(description, curToken, sizeof (char *)); } printf("Description: %s \n",description); break; } if (findEntryExists(head, surname) != NULL) printf("\nAn entry for <%s %s> is already in the catalog!\nNew entry not entered.\n",short_name,surname); else { printf("\nTry to entry <%s %s %d %s> in the catalog list!\n",short_name,surname,amount,description); InsertSort(&head,short_name, surname, amount, description); printf("\n**Entry done!**\n"); } // Maintain the list in alphabetical order by surname. } /********Uses special case code for the head end********/ void SortedInsert(catalog** headRef, catalogPointer newNode,char short_name[],char surname[],signed int amount,char description[]) { strcpy(newNode->short_name, short_name); strcpy(newNode->surname, surname); newNode->amount=amount; strcpy(newNode->description, description); // Special case for the head end if (*headRef == NULL||(*headRef)->surname >= newNode->surname) { newNode->next = *headRef; *headRef = newNode; } else { // Locate the node before the point of insertion catalogPointer current = *headRef; catalogPointer temp=current->next; while ( temp!=NULL ) { if(strcmp(temp->surname,newNode->surname)<0 ) current = temp; } newNode->next = temp; temp = newNode; } } // Given a list, change it to be in sorted order (using SortedInsert()). void InsertSort(catalog** headRef,char short_name[],char surname[],signed int amount,char description[]) { catalogPointer result = NULL; // build the answer here catalogPointer current = *headRef; // iterate over the original list catalogPointer next; while (current!=NULL) { next = current->next; // tricky - note the next pointer before we change it SortedInsert(&result,current,short_name,surname,amount,description); current = next; } *headRef = result; } Running the program I get these strange things (garbage?)... Choose your selection: enter james bond 007 gun Your command is: enter james bond 007 gun temp is:james What you entered for saving: Short Name: james SurName: Amount: 0 Description: 0T?? Try to entry james 0 0T?? in the catalog list! Entry done! Also I'm facing a problem on how to use the 'malloc' on this program. Thanks in advance. . .

    Read the article

  • test cases for testing a strtok-alike function [C++]

    - by Neeraj
    Consider the following class definition: class StrToTokens { StrToTokens(const char* str, const char* delimiters = "\t\r\n"); //constructor string getNextToken(); void reset(); bool empty(); } Can someone list some good testcases to test the above class. A few I could think of are: empty string, empty delimiters, repeated delimiters, consecutive delimiters, string with only delimiters. However, the interviewer expected some more(better ones). Can you help out. Thanks.

    Read the article

  • Removing first two elements of a string array in C

    - by sandeep p
    How can I remove first two elements of a string array? I have a code which is something like this. char *x[10]; .............. .............. .............. char *event[20]; event[0]=strtok(x[i]," "); event[1]=strtok(NULL," "); event[2]=strtok(NULL," "); event[3]=strtok(NULL," "); event[4]=strtok(NULL," "); event[5]=strtok(NULL," "); for(i=2;i<length;i++) { strcpy(event[i-2],event[i]); } I observed that only event[0] has proper values. I printed the contents of event[][] before for loop and it displays correctly. Could you please tell me why this is wrong? and a possible solution?

    Read the article

  • Double split in C

    - by Dmitri
    Hi again dear community! OK. For example I have this line in my txt file: 1|1,12;7,19;6,4;8,19;2,2 . As you can see, it has 2 parts, separated by "|". I have no problems getting both parts, and separating second part ( 1,12;7,19;6,4;8,19;2,2 ) using ";" separator. BUT I do have problems with separating further by "," to get first and second number of each set. This is my current code: result = strtok(result, ";"); while(result != NULL ) { printf("%s\n", result); result = strtok(NULL, ";"); } It outputs me: 1,12 7,19 6,4 8,19 2,2 OK, great. But when I try to 'strtok' (I'm using this method for splitting) like this: result = strtok(result, ";"); while(result != NULL ) { //printf("%s\n", result); help = strtok(result, ","); while(help != NULL) { printf("<%s>", help); help = strtok(NULL, ","); } result = strtok(NULL, ";"); } I only get "<1,<12" like there is only one set in this set of numbers. I dont understand where are the rest of the numbers. Instead, output should be: <1,<12,<7,<19,<6,<4,<8,<19,<2,<2. Could someone please give a solution, how to get EACH number of each set this set of numbers. Maybe there are other methods or I'm doing something wrong :) Thank you! Best Regards, Dmitri

    Read the article

  • Why wont my while loop take new input (c++)

    - by Van
    I've written a program to get a string input from a user and parse it into tokens and move a robot according to the input. My problem is trying to issue more than one command. The code looks like: void Navigator::manualDrive() { const int bufSize = 42; char uinput[bufSize]; char delim[] = " "; char *token; while(true) { Navigator::parseInstruction(uinput); } } /* parseInstruction(char *c) -- parses cstring instructions received * and moves robot accordingly */ void Navigator::parseInstruction(char * c) { const int bufSize = 42; char uinput[bufSize]; char delim[] = " "; char *token; cout << "Enter your directions below: \n"; cin.ignore(); cin.getline (uinput, bufSize); token=strtok(uinput, delim); if(strcmp("forward", token) == 0) { int inches; token = strtok(NULL, delim); inches = atoi (token); Navigator::travel(inches); } if(strcmp("back",token) == 0) { int inches; token = strtok(NULL, delim); inches = atoi (token); double value = fabs(0.0735 * fabs(inches) - 0.0550); myRobot.backward(1/*speed*/, value/*time*/); } if(strcmp("turn",token) == 0) { int degrees; token = strtok(NULL, delim); if(strcmp("left",token) == 0) { token = strtok(uinput, delim); degrees = atoi (token); double value = fabs(0.0041 * degrees - 0.0523); myRobot.turnLeft(1/*speed*/, value/*time*/); } } if(strcmp("turn",token) == 0) { int degrees; token = strtok(NULL, delim); if(strcmp("right",token) == 0) { token = strtok(uinput, delim); degrees = atoi (token); double value = fabs(0.0041 * degrees - 0.0523); myRobot.turnRight(1/*speed*/, value/*time*/); } } if(strcmp("stop",token) == 0) { myRobot.motors(0,0); } } In the function manualDrive I have a while loop calling the function parseInstruction infinitely. The program outputs "Enter your directions below: " When I give the program instructions it executes them, and then it outputs "enter your directions below: " again and when I input my directions again it does not execute them and outputs "Enter your directions below: " instead. I'm sure this is a very simple fix I'm just very new to c++. So if you could please help me out and tell me why the program only takes the first set of directions. thanks

    Read the article

  • Why wont my while loop wont take new input (c++)

    - by Van
    I've written a program to get a string input from a user and parse it into tokens and move a robot according to the input. My problem is trying to issue more than one command. The code looks like: void Navigator::manualDrive() { const int bufSize = 42; char uinput[bufSize]; char delim[] = " "; char *token; while(true) { Navigator::parseInstruction(uinput); } } /* parseInstruction(char *c) -- parses cstring instructions received * and moves robot accordingly */ void Navigator::parseInstruction(char * c) { const int bufSize = 42; char uinput[bufSize]; char delim[] = " "; char *token; cout << "Enter your directions below: \n"; cin.ignore(); cin.getline (uinput, bufSize); token=strtok(uinput, delim); if(strcmp("forward", token) == 0) { int inches; token = strtok(NULL, delim); inches = atoi (token); Navigator::travel(inches); } if(strcmp("back",token) == 0) { int inches; token = strtok(NULL, delim); inches = atoi (token); double value = fabs(0.0735 * fabs(inches) - 0.0550); myRobot.backward(1/*speed*/, value/*time*/); } if(strcmp("turn",token) == 0) { int degrees; token = strtok(NULL, delim); if(strcmp("left",token) == 0) { token = strtok(uinput, delim); degrees = atoi (token); double value = fabs(0.0041 * degrees - 0.0523); myRobot.turnLeft(1/*speed*/, value/*time*/); } } if(strcmp("turn",token) == 0) { int degrees; token = strtok(NULL, delim); if(strcmp("right",token) == 0) { token = strtok(uinput, delim); degrees = atoi (token); double value = fabs(0.0041 * degrees - 0.0523); myRobot.turnRight(1/*speed*/, value/*time*/); } } if(strcmp("stop",token) == 0) { myRobot.motors(0,0); } } In the function manualDrive I have a while loop calling the function parseInstruction infinitely. The program outputs "Enter your directions below: " When I give the program instructions it executes them, and then it outputs "enter your directions below: " again and when I input my directions again it does not execute them and outputs "Enter your directions below: " instead. I'm sure this is a very simple fix I'm just very new to c++. So if you could please help me out and tell me why the program only takes the first set of directions. thanks

    Read the article

  • How to draw flowchart for code involving opening from text file and reading them

    - by problematic
    like this code fp1=fopen("Fruit.txt","r"); if(fp1==NULL) { printf("ERROR in opening file\n"); return 1; } else { for(i=0;i<lines;i++)//reads Fruits.txt database { fgets(product,sizeof(product),fp1); id[i]=atoi(strtok(product,",")); strcpy(name[i],strtok(NULL,",")); price[i]=atof(strtok(NULL,",")); stock[i]=atoi(strtok(NULL,"\n")); } } fclose(fp1); These symbols sound too similar to differentiate their function,can anyone helps me by any method, or use names of shape according to this site http://www.breezetree.com/article-excel-flowchart-shapes.htm

    Read the article

  • Why does my token return NULL and how can I fix it?(c++)

    - by Van
    I've created a program to get a string input from a user and parse it into tokens and move a robot according to the input. The program is supposed to recognize these inputs(where x is an integer): "forward x" "back x" "turn left x" "turn right x" and "stop". The program does what it's supposed to for all commands except for "stop". When I type "stop" the program prints out "whats happening?" because I've written a line which states: if(token == NULL) { cout << "whats happening?" << endl; } Why does token get NULL, and how can I fix this so it will read "stop" properly? here is the code: bool stopper = 0; void Navigator::manualDrive() { VideoStream video(&myRobot, 0);//allows user to see what robot sees video.startStream(); const int bufSize = 42; char uinput[bufSize]; char delim[] = " "; char *token; while(stopper == 0) { cout << "Enter your directions below: " << endl; cin.getline(uinput,bufSize); Navigator::parseInstruction(uinput); } } /* parseInstruction(char *c) -- parses cstring instructions received * and moves robot accordingly */ void Navigator::parseInstruction(char * uinput) { char delim[] = " "; char *token; // cout << "Enter your directions below: " << endl; // cin.getline (uinput, bufSize); token=strtok(uinput, delim); if(token == NULL) { cout << "whats happening?" << endl; } if(strcmp("forward", token) == 0) { int inches; token = strtok(NULL, delim); inches = atoi (token); double value = fabs(0.0735 * fabs(inches) - 0.0550); myRobot.forward(1, value); } else if(strcmp("back",token) == 0) { int inches; token = strtok(NULL, delim); inches = atoi (token); double value = fabs(0.0735 * fabs(inches) - 0.0550); myRobot.backward(1/*speed*/, value/*time*/); } else if(strcmp("turn",token) == 0) { int degrees; token = strtok(NULL, delim); if(strcmp("left",token) == 0) { token = strtok(uinput, delim); degrees = atoi (token); double value = fabs(0.00467 * degrees - 0.04); myRobot.turnLeft(1/*speed*/, value/*time*/); } else if(strcmp("right",token) == 0) { token = strtok(uinput, delim); degrees = atoi (token); double value = fabs(0.00467 * degrees - 0.04); myRobot.turnRight(1/*speed*/, value/*time*/); } } else if(strcmp("stop",token) == 0) { stopper = 1; } else { std::cerr << "Unknown command '" << token << "'\n"; } } /* autoDrive() -- reads in file from ifstream, parses * and moves robot according to instructions in file */ void Navigator::autoDrive(string filename) { const int bufSize = 42; char fLine[bufSize]; ifstream infile; infile.open("autodrive.txt", fstream::in); while (!infile.eof()) { infile.getline(fLine, bufSize); Navigator::parseInstruction(fLine); } infile.close(); } I need this to break out of the while loop and end manualDrive because in my driver program the next function called is autoDrive.

    Read the article

1 2 3 4  | Next Page >