Search Results

Search found 168 results on 7 pages for 'strcmp'.

Page 5/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • Detect if an instance is running with kernel32::CreateMutexA

    - by moz
    Hello. I'm working on an NSIS installer, and trying to check if a certain application is running before uninstalling. So, I use kernel32::CreateMutexA call. Here is the chunk: System::Call 'kernel32::CreateMutexA(i 0, i 0, t "cmd.exe") i .r1 ?e' Pop $R0 StrCmp $R0 0 +3 MessageBox MB_USERICON "The application is already running." Abort I put it into un.onInit. Trouble is, the process (cmd.exe here) is never detected. Did I miss something? Tx.

    Read the article

  • C++ sort array of char pointers

    - by user69514
    Can you tell me what's wrong with my method? I ends up putting the same thing everywhre and it's actually not sorting. void sortArrays(){ int i, j; for(i=0; i<counter; i++){ for( j=0; j<i; j++){ if( strcmp(title_arr[i], title_arr[j]) < 0){ char* title_temp = title_arr[i]; title_arr[j] = title_temp; } } }

    Read the article

  • Checking for an "end of line" in a C-string

    - by Numerator
    I would really love your help with the following problem: I want to get as an input from the user a maximum length of 30 chars string and check whether it contains an end of line. This is what I tried to write so far: int main(void) { int i; char* command = (char*)calloc(31, sizeof(char)); while (0 < 1) { scanf("%s", command); for (i = 0; i <= strlen(command); ++i) { if (command[i] == '\n') printf("here"); } if (strcmp(command, "quit") == 0) break; } The idea is to check whether the command given by the user as input is "legal" - that is of length < 31. when i run this code, it never prints "here" regardless of the length of input.

    Read the article

  • sorting set of five string in alphabetical oder throwing warning?

    - by rost rost
    sorting set of five string in alphabetical oder throwing warning ?my code is below please help me to fix it #include<stdio.h> #include<string.h> int main() { char a[5][20],t[20]; int i,j; printf("enter 5 string\n") scanf("%s",a); for(i=1;i<5;i++) { for(j=1;j<5;j++) { if(strcmp(a[j-1],a[j])>0) { strcpy (t,a[j-1]); strcpy (a[j-1],a[j]); strcpy(a[j],t); } } } for(i=1;i<5;i++) printf("%s\n",a[i]); } ~

    Read the article

  • Inserting Records in Ascending Order function- C homework assignment

    - by Aaron McRuer
    Good day, Stack Overflow. I have a homework assignment that I'm working on this weekend that I'm having a bit of a problem with. We have a struct "Record" (which contains information about cars for a dealership) that gets placed in a particular spot in a linked list according to 1) its make and 2) according to its model year. This is done when initially building the list, when a "int insertRecordInAscendingOrder" function is called in Main. In "insertRecordInAscendingOrder", a third function, "createRecord" is called, where the linked list is created. The function then goes to the function "compareCars" to determine what elements get put where. Depending on the value returned by this function, insertRecordInAscendingOrder then places the record where it belongs. The list is then printed out. There's more to the assignment, but I'll cross that bridge when I come to it. Ideally, and for the assignment to be considered correct, the linked list must be ordered as: Chevrolet 2012 25 Chevrolet 2013 10 Ford 2010 5 Ford 2011 3 Ford 2012 15 Honda 2011 9 Honda 2012 3 Honda 2013 12 Toyota 2009 2 Toyota 2011 7 Toyota 2013 20 from the a text file that has the data ordered the following way: Ford 2012 15 Ford 2011 3 Ford 2010 5 Toyota 2011 7 Toyota 2012 20 Toyota 2009 2 Honda 2011 9 Honda 2012 3 Honda 2013 12 Chevrolet 2013 10 Chevrolet 2012 25 Notice that the alphabetical order of the "make" field takes precedence, then, the model year is arranged from oldest to newest. However, the program produces this as the final list: Chevrolet 2012 25 Chevrolet 2013 10 Honda 2011 9 Honda 2012 3 Honda 2013 12 Toyota 2009 2 Toyota 2011 7 Toyota 2012 20 Ford 2010 5 Ford 2011 3 Ford 2012 15 I sat down with a grad student and tried to work out all of this yesterday, but we just couldn't figure out why it was kicking the Ford nodes down to the end of the list. Here's the code. As you'll notice, I included a printList call at each instance of the insertion of a node. This way, you can see just what is happening when the nodes are being put in "order". It is in ANSI C99. All function calls must be made as they are specified, so unfortunately, there's no real way of getting around this problem by creating a more efficient algorithm. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LINE 50 #define MAX_MAKE 20 typedef struct record { char *make; int year; int stock; struct record *next; } Record; int compareCars(Record *car1, Record *car2); void printList(Record *head); Record* createRecord(char *make, int year, int stock); int insertRecordInAscendingOrder(Record **head, char *make, int year, int stock); int main(int argc, char **argv) { FILE *inFile = NULL; char line[MAX_LINE + 1]; char *make, *yearStr, *stockStr; int year, stock, len; Record* headRecord = NULL; /*Input and file diagnostics*/ if (argc!=2) { printf ("Filename not provided.\n"); return 1; } if((inFile=fopen(argv[1], "r"))==NULL) { printf("Can't open the file\n"); return 2; } /*obtain values for linked list*/ while (fgets(line, MAX_LINE, inFile)) { make = strtok(line, " "); yearStr = strtok(NULL, " "); stockStr = strtok(NULL, " "); year = atoi(yearStr); stock = atoi(stockStr); insertRecordInAscendingOrder(&headRecord,make, year, stock); } printf("The original list in ascending order: \n"); printList(headRecord); } /*use strcmp to compare two makes*/ int compareCars(Record *car1, Record *car2) { int compStrResult; compStrResult = strcmp(car1->make, car2->make); int compYearResult = 0; if(car1->year > car2->year) { compYearResult = 1; } else if(car1->year == car2->year) { compYearResult = 0; } else { compYearResult = -1; } if(compStrResult == 0 ) { if(compYearResult == 1) { return 1; } else if(compYearResult == -1) { return -1; } else { return compStrResult; } } else if(compStrResult == 1) { return 1; } else { return -1; } } int insertRecordInAscendingOrder(Record **head, char *make, int year, int stock) { Record *previous = *head; Record *newRecord = createRecord(make, year, stock); Record *current = *head; int compResult; if(*head == NULL) { *head = newRecord; printf("Head is null, list was empty\n"); printList(*head); return 1; } else if ( compareCars(newRecord, *head)==-1) { *head = newRecord; (*head)->next = current; printf("New record was less than the head, replacing\n"); printList(*head); return 1; } else { printf("standard case, searching and inserting\n"); previous = *head; while ( current != NULL &&(compareCars(newRecord, current)==1)) { printList(*head); previous = current; current = current->next; } printList(*head); previous->next = newRecord; previous->next->next = current; } return 1; } /*creates records from info passed in from main via insertRecordInAscendingOrder.*/ Record* createRecord(char *make, int year, int stock) { printf("CreateRecord\n"); Record *theRecord; int len; if(!make) { return NULL; } theRecord = malloc(sizeof(Record)); if(!theRecord) { printf("Unable to allocate memory for the structure.\n"); return NULL; } theRecord->year = year; theRecord->stock = stock; len = strlen(make); theRecord->make = malloc(len + 1); strncpy(theRecord->make, make, len); theRecord->make[len] = '\0'; theRecord->next=NULL; return theRecord; } /*prints list. lists print.*/ void printList(Record *head) { int i; int j = 50; Record *aRecord; aRecord = head; for(i = 0; i < j; i++) { printf("-"); } printf("\n"); printf("%20s%20s%10s\n", "Make", "Year", "Stock"); for(i = 0; i < j; i++) { printf("-"); } printf("\n"); while(aRecord != NULL) { printf("%20s%20d%10d\n", aRecord->make, aRecord->year, aRecord->stock); aRecord = aRecord->next; } printf("\n"); } The text file you'll need for a command line argument can be saved under any name you like; here are the contents you'll need: Ford 2012 15 Ford 2011 3 Ford 2010 5 Toyota 2011 7 Toyota 2012 20 Toyota 2009 2 Honda 2011 9 Honda 2012 3 Honda 2013 12 Chevrolet 2013 10 Chevrolet 2012 25 Thanks in advance for your help. I shall continue to plow away at it myself.

    Read the article

  • C - check if string is a substring of another string

    - by user69514
    I need to write a program that takes two strings as arguments and check if the second one is a substring of the first one. I need to do it without using any special library functions. I created this implementation, but I think it's always returning true as long as there is one letter that's the same in both strings. Can you help me out here. I'm not sure what I am doing wrong: #include <stdio.h> #include <string.h> int my_strstr( char const *s, char const *sub ) { char const *ret = sub; int r = 0; while ( ret = strchr( ret, *sub ) ) { if ( strcmp( ++ret, sub+1 ) == 0 ){ r = 1; } else{ r = 0; } } return r; } int main(int argc, char **argv){ if (argc != 3) { printf ("Usage: check <string one> <string two>\n"); } int result = my_strstr(argv[1], argv[2]); if(result == 1){ printf("%s is a substring of %s\n", argv[2], argv[1]); } else{ printf("%s is not a substring of %s\n", argv[2], argv[1]); } return 0; }

    Read the article

  • How to copy file using NSIS ?

    - by Xinus
    I want to copy war file to tomcat web-app directory using NSIS setup. I have successfully installed tomcat and jdk using following script !define PRODUCT_NAME "App Deploy" !define PRODUCT_VERSION "1.0" !define PRODUCT_PUBLISHER "ZippySoft" SetCompressor lzma ;!include "UserManagement.nsh" ; MUI 1.67 compatible ------ !include "MUI.nsh" ; MUI Settings !define MUI_ABORTWARNING ;!define MUI_ICON "${NSISDIR}\Contrib\Graphics\Icons\modern-install.ico" ; Welcome page !insertmacro MUI_PAGE_WELCOME ; Components page !insertmacro MUI_PAGE_COMPONENTS ; Instfiles page !insertmacro MUI_PAGE_INSTFILES ; Finish page !insertmacro MUI_PAGE_FINISH ; Language files !insertmacro MUI_LANGUAGE "English" ; Reserve files !insertmacro MUI_RESERVEFILE_INSTALLOPTIONS ; MUI end ------ Name "${PRODUCT_NAME} ${PRODUCT_VERSION}" OutFile "AppDeploy.exe" InstallDir "$PROGRAMFILES\App Deploy" ShowInstDetails show ;Section -SETTINGS ; SetOutPath "$INSTDIR" ; SetOverwrite ifnewer ;SectionEnd ;Section "JDK" SEC01 ; File "Prerequisites\jdk-1_5_0_15-windows-i586-p.exe" ; ExecWait "$INSTDIR\jdk-1_5_0_15-windows-i586-p.exe" ;SectionEnd ;System::Call 'Kernel32::SetEnvironmentVariableA(t, t) i("name", "value").r0' ;StrCmp $0 0 error ; ExecWait ProgThatReadsEnv.exe ; Goto done ;error: ; MessageBox MB_OK "Can't set environment variable" ;done: ;Section "Tomcat" SEC02 ; File "Prerequisites\apache-tomcat-6.0.16.exe" ; ExecWait "$INSTDIR\apache-tomcat-6.0.16.exe" ;SectionEnd Section "Data Submission Tool" SEC03 File "Prerequisites\DataSubmissionToolFinal.war" CopyFiles `$INSTDIR\DataSubmissionToolFinal.war` `c:\DataSubmissionToolFinal.war` StrCpy $0 "$INSTDIR\DataSubmissionToolFinal.war" ;Path of copy file from StrCpy $1 "c:\DataSubmissionToolFinal.war" ;Path of copy file to StrCpy $2 1 ; only 0 or 1, set 0 to overwrite file if it already exists System::Call 'kernel32::CopyFile(t r0, t r1, b r2) l' Pop $0 ; pops a bool. if overwrite is off and there is a file then error will be 1 SectionEnd There are no script errors but war file is not getting copied to c drive . How to do it? Also is it possible to identify path to JDK and Tomcat installation using NSIS ? Sorry if the question is too obvious, I am quite new to NSIS..

    Read the article

  • Cache Simulator in C

    - by DuffDuff
    Ok this is only my second question, and it's quite a doozy. It's for a school assignment, but no one (including the TAs) seems to be able to help me. It's kind of a tall order but I'm not sure where else to turn. Essentially the assignment was to make a cache simulator. This version is direct mapping and is actually only a small portion of the whole project, but if I can't even get this down I have no chance with other associativities. I'm posting my whole code because I don't want to make any assumptions about where the problem is. This is the test case: http://www.mediafire.com/?ty5dnihydnw And you run the following command: ./sims 512 direct 32 fifo wt pinatrace.out You're supposed to get: hits: 604037 misses 138349 writes: 239269 reads: 138349 But I get: Hits: 587148 Misses: 155222 Writes: 239261 Reads: 155222 If anyone could at least point me in the right direction it would be greatly appreciated. I've been stuck on this for about 12 hours. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> struct myCache { int valid; char *tag; char *block; }; /* sim [-h] <cache size> <associativity> <block size> <replace alg> <write policy> <trace file> */ //God willing I come up with a better Hex to Bin convertion that maintains the beginning 0s... void hex2bin(char input[], char output[]) { int i; int a = 0; int b = 1; int c = 2; int d = 3; int x = 4; int size; size = strlen(input); for (i = 0; i < size; i++) { if (input[i] =='0') { output[i*x +a] = '0'; output[i*x +b] = '0'; output[i*x +c] = '0'; output[i*x +d] = '0'; } else if (input[i] =='1') { output[i*x +a] = '0'; output[i*x +b] = '0'; output[i*x +c] = '0'; output[i*x +d] = '1'; } else if (input[i] =='2') { output[i*x +a] = '0'; output[i*x +b] = '0'; output[i*x +c] = '1'; output[i*x +d] = '0'; } else if (input[i] =='3') { output[i*x +a] = '0'; output[i*x +b] = '0'; output[i*x +c] = '1'; output[i*x +d] = '1'; } else if (input[i] =='x') { output[i*x +a] = '0'; output[i*x +b] = '1'; output[i*x +c] = '0'; output[i*x +d] = '0'; } else if (input[i] =='5') { output[i*x +a] = '0'; output[i*x +b] = '1'; output[i*x +c] = '0'; output[i*x +d] = '1'; } else if (input[i] =='6') { output[i*x +a] = '0'; output[i*x +b] = '1'; output[i*x +c] = '1'; output[i*x +d] = '0'; } else if (input[i] =='7') { output[i*x +a] = '0'; output[i*x +b] = '1'; output[i*x +c] = '1'; output[i*x +d] = '1'; } else if (input[i] =='8') { output[i*x +a] = '1'; output[i*x +b] = '0'; output[i*x +c] = '0'; output[i*x +d] = '0'; } else if (input[i] =='9') { output[i*x +a] = '1'; output[i*x +b] = '0'; output[i*x +c] = '0'; output[i*x +d] = '1'; } else if (input[i] =='a') { output[i*x +a] = '1'; output[i*x +b] = '0'; output[i*x +c] = '1'; output[i*x +d] = '0'; } else if (input[i] =='b') { output[i*x +a] = '1'; output[i*x +b] = '0'; output[i*x +c] = '1'; output[i*x +d] = '1'; } else if (input[i] =='c') { output[i*x +a] = '1'; output[i*x +b] = '1'; output[i*x +c] = '0'; output[i*x +d] = '0'; } else if (input[i] =='d') { output[i*x +a] = '1'; output[i*x +b] = '1'; output[i*x +c] = '0'; output[i*x +d] = '1'; } else if (input[i] =='e') { output[i*x +a] = '1'; output[i*x +b] = '1'; output[i*x +c] = '1'; output[i*x +d] = '0'; } else if (input[i] =='f') { output[i*x +a] = '1'; output[i*x +b] = '1'; output[i*x +c] = '1'; output[i*x +d] = '1'; } } output[32] = '\0'; } int main(int argc, char* argv[]) { FILE *tracefile; char readwrite; int trash; int cachesize; int blocksize; int setnumber; int blockbytes; int setbits; int blockbits; int tagsize; int m; int count = 0; int count2 = 0; int count3 = 0; int i; int j; int xindex; int jindex; int kindex; int lindex; int setadd; int totalset; int writeMiss = 0; int writeHit = 0; int cacheMiss = 0; int cacheHit = 0; int read = 0; int write = 0; int size; int extra; char bbits[100]; char sbits[100]; char tbits[100]; char output[100]; char input[100]; char origtag[100]; if (argc != 7) { if (strcmp(argv[0], "-h")) { printf("./sim2 <cache size> <associativity> <block size> <replace alg> <write policy> <trace file>\n"); return 0; } else { fprintf(stderr, "Error: wrong number of parameters.\n"); return -1; } } tracefile = fopen(argv[6], "r"); if(tracefile == NULL) { fprintf(stderr, "Error: File is NULL.\n"); return -1; } //Determining size of sbits, bbits, and tag cachesize = atoi(argv[1]); blocksize = atoi(argv[3]); setnumber = (cachesize/blocksize); printf("setnumber: %d\n", setnumber); setbits = (round((log(setnumber))/(log(2)))); printf("sbits: %d\n", setbits); blockbits = log(blocksize)/log(2); printf("bbits: %d\n", blockbits); tagsize = 32 - (blockbits + setbits); printf("t: %d\n", tagsize); struct myCache newCache[setnumber]; //Allocating Space for Tag Bits, initiating tag and valid to 0s for(i=0;i<setnumber;i++) { newCache[i].tag = (char *)malloc(sizeof(char)*(tagsize+1)); for(j=0;j<tagsize;j++) { newCache[i].tag[j] = '0'; } newCache[i].valid = 0; } while(fgetc(tracefile)!='#') { setadd = 0; totalset = 0; //read in file fseek(tracefile,-1,SEEK_CUR); fscanf(tracefile, "%x: %c %s\n", &trash, &readwrite, origtag); //shift input Hex size = strlen(origtag); extra = (10 - size); for(i=0; i<extra; i++) input[i] = '0'; for(i=extra, j=0; i<(size-(2-extra)); j++, i++) input[i]=origtag[j+2]; input[8] = '\0'; // Convert Hex to Binary hex2bin(input, output); //Resolving the Address into tbits, sbits, bbits for (xindex=0, jindex=(32-blockbits); jindex<32; jindex++, xindex++) { bbits[xindex] = output[jindex]; } bbits[xindex]='\0'; for (xindex=0, kindex=(32-(blockbits+setbits)); kindex<32-(blockbits); kindex++, xindex++){ sbits[xindex] = output[kindex]; } sbits[xindex]='\0'; for (xindex=0, lindex=0; lindex<(32-(blockbits+setbits)); lindex++, xindex++){ tbits[xindex] = output[lindex]; } tbits[xindex]='\0'; //Convert set bits from char array into ints for(xindex = 0, kindex = (setbits -1); xindex < setbits; xindex ++, kindex--) { if (sbits[xindex] == '1') setadd = 1; if (sbits[xindex] == '0') setadd = 0; setadd = setadd * pow(2, kindex); totalset += setadd; } //Calculating Hits and Misses if (newCache[totalset].valid == 0) { newCache[totalset].valid = 1; strcpy(newCache[totalset].tag, tbits); } else if (newCache[totalset].valid == 1) { if(strcmp(newCache[totalset].tag, tbits) == 0) { if (readwrite == 'W') { cacheHit++; write++; } if (readwrite == 'R') cacheHit++; } else { if (readwrite == 'R') { cacheMiss++; read++; } if (readwrite == 'W') { cacheMiss++; read++; write++; } strcpy(newCache[totalset].tag, tbits); } } } printf("Hits: %d\n", cacheHit); printf("Misses: %d\n", cacheMiss); printf("Writes: %d\n", write); printf("Reads: %d\n", read); }

    Read the article

  • Hiding keyboard in iPad with UITextView , can do this in iphone not iPad.

    - by user271753
    Hey the code below when written in HelloWorldAppDelegate.m in an iPhone app having UITextView hides the keyboard when the app starts : The UITextView is editable thats what I want in iPad Also But how can do the same in iPad its not working at all ! ! ! ! ! ! ! And also I have checked that I can use Subviews if I want to keep this to my app itself - (void)applicationDidFinishLaunching:(UIApplication *)application { //For hiding the Keyboard [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [window addSubview:viewController.view]; [window makeKeyAndVisible]; } /// /// Hiding the Keyboard /// - (void)keyboardWillShow:(NSNotification *)note { //The UIWindow that contains the keyboard view UIWindow* tempWindow; //Because we cant get access to the UIKeyboard throught the SDK we will just use UIView. //UIKeyboard is a subclass of UIView anyways UIView* keyboard; //Check each window in our application for(int c = 0; c < [[[UIApplication sharedApplication] windows] count]; c ++) { //Get a reference of the current window tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:c]; //Get a reference of the current view for(int i = 0; i < [tempWindow.subviews count]; i++) { keyboard = [tempWindow.subviews objectAtIndex:i]; if (!strcmp(object_getClassName(keyboard), "UIKeyboard")) { NSLog(@"hide keyboard"); [keyboard setHidden:YES]; return; } } } } Regards

    Read the article

  • Linux Kernel - Red/Black Trees

    - by CodeRanger
    I'm trying to implement a red/black tree in Linux per task_struct using code from linux/rbtree.h. I can get a red/black tree inserting properly in a standalone space in the kernel such as a module but when I try to get the same code to function with the rb_root declared in either task_struct or task_struct-files_struct, I get a SEGFAULT everytime I try an insert. Here's some code: In task_struct I create a rb_root struct for my tree (not a pointer). In init_task.h, macro INIT_TASK(tsk), I set this equal to RB_ROOT. To do an insert, I use this code: rb_insert(&(current-fd_tree), &rbnode); This is where the issue occurs. My insert command is the standard insert that is documented in all RBTree documentation for the kernel: int my_insert(struct rb_root *root, struct mytype *data) { struct rb_node **new = &(root->rb_node), *parent = NULL; /* Figure out where to put new node */ while (*new) { struct mytype *this = container_of(*new, struct mytype, node); int result = strcmp(data->keystring, this->keystring); parent = *new; if (result < 0) new = &((*new)->rb_left); else if (result > 0) new = &((*new)->rb_right); else return FALSE; } /* Add new node and rebalance tree. */ rb_link_node(&data->node, parent, new); rb_insert_color(&data->node, root); return TRUE; } Is there something I'm missing? Some reason this would work fine if I made a tree root outside of task_struct? If I make rb_root inside of a module this insert works fine. But once I put the actual tree root in the task_struct or even in the task_struct-files_struct, I get a SEGFAULT. Can a root node not be added in these structs? Any tips are greatly appreciated. I've tried nearly everything I can think of.

    Read the article

  • Singleton with inheritance, Derived class is not able to get instantiated in parent?

    - by yesraaj
    Below code instantiates a derived singleton object based on environment variable. The compiler errors saying error C2512: 'Dotted' : no appropriate default constructor. I don't understand what the compiler is complaining about. #include <stdlib.h> #include <iostream> #include <string> using namespace std; class Dotted; class Singleton{ public: static Singleton instant(){ if (!instance_) { char * style = getenv("STYLE"); if (!style){ if (strcmp(style,"dotted")==0) { instance_ = new Dotted(); return *instance_; } } else{ instance_ = new Singleton(); return *instance_; } } return *instance_; } void print(){cout<<"Singleton";} ~Singleton(){}; protected: Singleton(){}; private: static Singleton * instance_; Singleton(const Singleton & ); void operator=(const Singleton & ); }; class Dotted:public Singleton{ public: void print(){cout<<"Dotted";} protected: Dotted(); }; Dotted::Dotted():Singleton(){} int main(){ Singleton::instant().print(); cin.get(); }

    Read the article

  • Strcpy and malloc issues

    - by mrblippy
    Hi, i am having trouble getting a method relating to a linked list working, i get the errors: assignment makes pointer from integer without a cast and passing argument 1 of âstrcpyâ makes pointer from integer without a cast. i have tried to include all the relevant code, but let me know if you need more info. thanks. struct unit { char code[5]; char *name; node_ptr students; }; typedef struct node *node_ptr; struct node { int student_id; char *studentname; node_ptr next; }; void enrol_student(struct unit u[], int n) { int i, p; int student_id = 0; char code_to_enrol[7]; char buffer[100]; node_ptr studentslist; scanf("%s\n", code_to_enrol); for(i=0; i <= n; i++) { studentslist = u[i].students; if(strcmp(u[i].code ,code_to_enrol)<=0) { scanf("enter student details %d %s\n", &studentID, buffer); p = (char *) malloc (strlen(buffer)+1); strcpy(p, buffer); insert_in_order(student_id, buffer, studentslist); } } } void insert_in_order(int n, char *i, node_ptr list) { node_ptr before = list; node_ptr students = (node_ptr) malloc(sizeof(struct node)); students->ID = n; students->name = *i; while(before->next && (before->next->ID < n)) { before = before->next; } students->next = before->next; before->next = students; }

    Read the article

  • Linked List Sorting with Strings In C

    - by user308583
    I have a struct, with a Name and a single Node called nextName It's a Singly Linked list, and my task is to create the list, based on alphabetical order of the strings. So iff i enter Joe Zolt and Arthur i should get my list structured as Joe Than Joe Zolt Than Arthur Joe Zolt I'm having trouble implementing the correct Algorithm, which would put the pointers in the right order. This is What I have as of Now. Temp would be the name the user just entered and is trying to put into the list, namebox is just a copy of my root, being the whole list if(temp != NULL) { struct node* namebox = root; while (namebox!=NULL && (strcmp((namebox)->name,temp->name) <= 0)) { namebox = namebox->nextName; printf("here"); } temp->nextName = namebox; namebox = temp; root = namebox; This Works right now, if i enter names like CCC BBB than AAA I Get Back AAA BBB CCC when i print But if i put AAA BBB CCC , When i print i only get CCC, it cuts the previous off.

    Read the article

  • "string" != "string"

    - by Misiur
    Hi. I'm doing some kind of own templates system. I want to change <title>{site('title')}</title> Into function "site" execution with parameter "title". Here's private function replaceFunc($subject) { foreach($this->func as $t) { $args = explode(", ", preg_replace('/\{'.$t.'\(\'([a-zA-Z,]+)\'\)\}/', '$1', $subject)); $subject = preg_replace('/\{'.$t.'\([a-zA-Z,\']+\)\}/', call_user_func_array($t, $args), $subject); } return $subject; } Here's site: function site($what) { global $db; $s = $db->askSingle("SELECT * FROM ".DB_PREFIX."config"); switch($what) { case 'title': return 'Title of page'; break; case 'version': return $s->version; break; case 'themeDir': return 'lolmao'; break; default: return false; } } I've tried to compare $what (which is for this case "title") with "title". MD5 are different. strcmp gives -1, "==", and "===" return false. What is wrong? ($what type is string. You can't change call_user_func_array into call_user_func, because later I'll be using multiple arguments)

    Read the article

  • problem with fork()

    - by john
    I'm writing a shell which forks, with the parent reading the input and the child process parsing and executing it with execvp. pseudocode of main method: do{ pid = fork(); print pid; if (p<0) { error; exit; } if (p>0) { wait for child to finish; read input; } else { call function to parse input; exit; } }while condition return; what happens is that i never seem to enter the child process (pid printed is always positive, i never enter the else). however, if i don't call the parse function and just have else exit, i do correctly enter parent and child alternatingly. full code: int main(int argc, char *argv[]){ char input[500]; pid_t p; int firstrun = 1; do{ p = fork(); printf("PID: %d", p); if (p < 0) {printf("Error forking"); exit(-1);} if (p > 0){ wait(NULL); firstrun = 0; printf("\n> "); bzero(input, 500); fflush(stdout); read(0, input, 499); input[strlen(input)-1] = '\0'; } else exit(0); else { if (parse(input) != 0 && firstrun != 1) { printf("Error parsing"); exit(-1); } exit(0); } }while(strcmp(input, "exit") != 0); return 0; }

    Read the article

  • c++ Mixing printf with wprintf (or cout with wcout)

    - by Bo Jensen
    I know you should not mix printing with printf,cout and wprintf,wcout, but have a hard time finding a good answer why and if it is possible to get round it. The problem is I use a external library that prints with printf and my own uses wcout. If I do a simple example it works fine, but from my full application it simply does not print the printf statements. If this is really a limitation, then there would be many libraries out there which can not work together with wide printing applications. Any insight on this is more than welcome. Update : I boiled it down to : #include <stdio.h> #include <stdlib.h> #include <iostream> #include <readline/readline.h> #include <readline/history.h> int main() { char *buf; std::wcout << std::endl; /* ADDING THIS LINE MAKES PRINTF VANISH!!! */ rl_bind_key('\t',rl_abort);//disable auto-complete while((buf = readline("my-command : "))!=NULL) { if (strcmp(buf,"quit")==0) break; std::wcout<<buf<< std::endl; if (buf[0]!=0) add_history(buf); } free(buf); return 0; } So I guess it might be a flushing problem, but it still looks strange to me, I have to check up on it.

    Read the article

  • Deleting a node from linked list in C

    - by LuckySlevin
    My problem is deleting a node from linked list. I have two structs : typedef struct inner_list { int count; char word[100]; inner_list*next; } inner_list; typedef struct outer_list { char word [100]; inner_list * head; int count; outer_list * next; } outer_list; My problem is in deleting a node from outer_list linked list. For example when user entered aaa to delete, delete function should find the node with outer_list->word = aaa and delete this node and reconnect the list again. I tried the below code to do this. but After finding and deleting I'm losing the list. I don't know what's wrong. Please notice that outer_list have also a linked list of inner_list inside. void delnode(outer_list *head,char num[100]) { outer_list *temp, *m; temp=head; while(temp!=NULL) { if(strcmp(temp->word==num)==0) { if(temp==head) { head=temp->next; free(temp); return; } else { m->next=temp->next; free(temp); return; } }else { m=temp; temp= temp->next; } } printf(" ELEMENT %s NOT FOUND ", num); } What are your ideas about this?

    Read the article

  • How to deal with Unicode strings in C/C++ in a cross-platform friendly way?

    - by Sorin Sbarnea
    On platforms different than Windows you could easily use char * strings and treat them as UTF-8. The problem is that on Windows you are required to accept and send messages using wchar* strings (W). If you'll use the ANSI functions (A) you will not support Unicode. So if you want to write truly portable application you need to compile it as Unicode on Windows. Now, In order to keep the code clean I would like to see what is the recommended way of dealing with strings, a way that minimize ugliness in the code. Type of strings you may need: std::string, std::wstring, std::tstring,char *,wchat_t *, TCHAR*, CString (ATL one). Issues you may encounter: cout/cerr/cin and their Unicode variants wcout,wcerr,wcin all renamed wide string functions and their TCHAR macros - like strcmp, wcscmp and _tcscmp. constant strings inside code, with TCHAR you will have to fill your code with _T() macros. What approach do you see as being best? (examples are welcome) Personally I would go for a std::tstring approach but I would like to see how would do to the conversions where they are necessary.

    Read the article

  • POSTmethod and PHP- login verification

    - by Neethusha
    I wrote a code for login verification..I got output with GET. But i need output with POST since it is more secure.pls let me know if there is any error in my code. javascript code: var xml; function verifyusernamepasswd(pass) { //pass is password that will be passed as parameter xml=new XMLHttpRequest(); var url="http://localhost/loginvalidate.php"; var para="q="+username+"&p="+pass;//username is global xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xml.setRequestHeader("Content-length", para.length); xml.setRequestHeader("Connection", "close"); xml.open("POST",url,true); xml.onreadystatechange=statechanged1; xml.send(para); } function statechanged1() { if(xml.readyState==4) alert(xml.responseText); } php code: <?php $username=$_POST["q"]; $password=$_POST["p"]; $con=mysql_connect("localhost","root","blaze"); if(!$con) { die('Could not connect: '.mysql.error()); } mysql_select_db("BLAZE",$con) or die("No such Db"); $result=mysql_query("SELECT Passwword FROM USERTABLE WHERE Userhandle='$username'"); if($result==null) echo "false"; else if($result!=null) { $row=mysql_fetch_array($result); if((strcmp($row['Passwword'],$password)==0)) echo "true"; else echo "false"; } ?> the verification does not return anything, cos my alert is not displayed at all...pls tell me whats wrong....

    Read the article

  • Segmentation fault on certain inputs and not others

    - by Brandon Schwandt
    Heres a function I wrote that has some debugging elements in it already. When i enter either a "y" or a "Y" as the input I get a segmentation fault during runtime. When I enter any other value the code runs. The seg fault kicks out after it scans and gives me the response but before the "scan worked" line is output. DOn't know why it would act like this only on these values. If anyone needs the function call I have that as well. query_user(char *response [10]) { printf("response after query call before clear=%s\n",response); strcpy(response,""); printf("response after clearing before scan=%s\n",response); printf("Enter another person into the line? y or n\n"); scanf("%s", response); printf("response after scan=%s\n",response); printf("scan worked"); } main() { char response [10]; strcpy(response,"y"); printf("response=%s\n",response); printf("When finished with program type \"done\" to exit\n"); while (strcmp(response,"done") != 0) { printf("response after while loop and before query call=%s\n",response); query_user(&response); } } output on error: response after query call before clear=y response after clearing before scan= Enter another person into the line? y or n y response after scan=y Segmentation Fault (core dumped) output on non-error: response after query call before clear=y response after clearing before scan= Enter another person into the line? y or n n response after scan=n scan worked Cycle number 0 (program continues to run outside this function)

    Read the article

  • Search string in file (C)

    - by chutsu
    So my code isn't working... test.c:27: warning: passing argument 1 of ‘search’ from incompatible pointer type which is the fgets line. My code opens a file, reads the file line by line, and I'm trying to create a "search" function that will return a value that indicates whether that string is found on that line of the file. My ultimate goal is to achieve a search and replace program. But one step at a time eh? this is what I have so far: #include <stdio.h> #include <string.h> int search(const char *content[], const char *search_term) { int t; for(t=0; content[t]; ++t){ if(!strcmp(content[t], search_term)){ return t; // found } } return 0; // not found } int main(int argc, char *argv[]) { FILE *file; char line[BUFSIZ]; int linenumber=0; char term[20] = "hello world"; file = fopen(argv[1], "r"); if(file != NULL){ while(fgets(line, sizeof(line), file)){ if(search(line, term) != -1){ printf("Search Term Found!!\n"); } ++linenumber; } } else{ perror(argv[1]); } fclose(file); return 0; }

    Read the article

  • Show only div of the product hovering in category grid with jQuery

    - by Dane
    On Magento, I'm trying to get avalable attributes per product in a new div (show/ hide onmouseover) as soon as I hover a product. Unfortunately, my jQuery code opens every div with the same name. I think, I need to do it with jQuery(this) but I tried it in a 1000 different ways, and it won't work. Maybe, somebody here can help me with a better code. jQuery(function() { jQuery('.slideDiv').hide().data('over', false); jQuery('#hover').hover(function() { jQuery('.slideDiv').fadeIn(); }, function() { // Check if mouse did not go over .dialog before hiding it again var timeOut = setTimeout(function() { if (!jQuery('.slideDiv').data('over')) { jQuery('.slideDiv').fadeOut(); clearTimeout(timeOut); } }, 100); }); // Set data for filtering on mouse events for #hover-here jQuery('.slideDiv').hover(function() { jQuery(this).data('over', true); }, function() { jQuery(this).fadeOut().data('over', false); }); }); The PHP just prints the attributes needed. <a href="#" id="hover">Custom Attributes</a> <div class="slideDiv"> <?php $attrs = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product); foreach($attrs as $attr) { if(0 == strcmp("shoe_size", $attr['attribute_code'])) { $options = $attr['values']; print "Größen:<br />"; foreach($options as $option) { print "{$option['store_label']}<br />"; } } } ?> </div> I added the script to [new link] http://jsfiddle.net/xsxfr/47/ so you can see there, that it is not working like this right now :(.

    Read the article

  • How to compare two structure strings in C++

    - by Arvandor
    Ok, so this week in class we're working with arrays. I've got an assignment that wanted me to create a structure for an employee containing an employee ID, first name, last name, and wages. Then it has me ask users for input for 5 different employees all stored in an array of this structure, then ask them for a search field type, then a search value. Lastly, display all the information for all positive search results. I'm still new, so I'm sure it isn't a terribly elegant program, but what I'm trying to do now is figure out how to compare a user entered string with the string stored in the structure... I'll try to give all the pertinent code below. struct employee { int empid, string firstname, string lastname, float wage }; employee emparray[] = {}; employee value[] = {}; //Code for populating emparray and structure, then determine search field etc. cout << "Enter a search value: "; cin >> value.lastname; for(i = 0; i < 5; i++) { if(strcmp(value.lastname.c_str, emparray[i].lastname.c_str) == 0) { output(); } } Which... I thought would work, but it's giving me the following error.. Error 1 error C3867: 'std::basic_string<_Elem,_Traits,_Alloc>::c_str': function call missing argument list; use '&std::basic_string<_Elem,_Traits,_Alloc>::c_str' to create a pointer to member d:\myfile Any thoughts on what's going on? Is there a way to compare two .name notated strings without totally revamping the program? IF you want to drill me on best practices, please feel free, but also please try to solve my particular problem.

    Read the article

  • Why do I need to close fds when reading and writing to the pipe?

    - by valentimsousa
    However, what if one of my processes needs to continuously write to the pipe while the other pipe needs to read? This example seems to work only for one write and one read. I need multi read and write void executarComandoURJTAG(int newSock) { int input[2], output[2], estado, d; pid_t pid; char buffer[256]; char linha[1024]; pipe(input); pipe(output); pid = fork(); if (pid == 0) {// child close(0); close(1); close(2); dup2(input[0], 0); dup2(output[1], 1); dup2(output[1], 2); close(input[1]); close(output[0]); execlp("jtag", "jtag", NULL); } else { // parent close(input[0]); close(output[1]); do { read(newSock, linha, 1024); /* Escreve o buffer no pipe */ write(input[1], linha, strlen(linha)); close(input[1]); while ((d = read(output[0], buffer, 255))) { //buffer[d] = '\0'; write(newSock, buffer, strlen(buffer)); puts(buffer); } write(newSock, "END", 4); } while (strcmp(linha, "quit") != 0); } }

    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

< Previous Page | 1 2 3 4 5 6 7  | Next Page >