bool BitcoinUnits::parse(int unit, const QString& value, CAmount* val_out) { if (!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); // Ignore spaces and thin spaces when parsing QStringList parts = removeSpaces(value).split("."); if (parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if (parts.size() > 1) { decimals = parts[1]; } if (decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if (str.size() > 18) { return false; // Longer numbers will exceed 63 bits } CAmount retvalue(str.toLongLong(&ok)); if (val_out) { *val_out = retvalue; } return ok; }
// Description // // Checks that the username is valid // // Parameters // // pszUsername - The username to test // // Returns // // Standard RESULT // static RESULT checkUsername(const char *pszUsername) { RESULT r = FAIL; char *pszTempUsername = strdup(pszUsername); if(NULL == pszTempUsername){ r = OUT_OF_MEMORY; trace(ERROR, __LINE__, "[Authy] Out of memory\n"); goto EXIT; } removeSpaces(pszTempUsername); if(strlen(pszTempUsername) <= 0){ r = FAIL; trace(ERROR, __LINE__, "[Authy] Invalid username %s=\n", pszUsername); goto EXIT; } r = OK; EXIT: cleanAndFree(pszTempUsername); pszTempUsername = NULL; return r; }
int main() { char str1[100],str2[100]; readline(str1,100); readline(str2,100); removeSpaces(str1); removeSpaces(str2); if(checkAnagram(str1,str2)==ANAGRAMS) { printf("Anagrams!\n"); } else { printf("Not Anagrams!\n"); } }
char *getNotificationString (ChatBot *bot) { char *str = malloc (bot->totalNotifications * 50); *str = 0; Notify **notify = bot->notify; for (int i = 0; i < bot->totalNotifications; i ++) { if (notify [i]->type == 1) { char *username = getUsernameByID (bot, notify [i]->userID); sprintf (str + strlen (str), "@"); sprintf (str + strlen (str), "%s", username); sprintf (str + strlen (str), " "); } else if (notify [i]->type == 0) { if (isUserInRoom (bot->room, notify [i]->userID)) { char *username = getUsernameByID (bot, notify [i]->userID); sprintf (str + strlen (str), "@"); sprintf (str + strlen (str), "%s", username); sprintf (str + strlen (str), " "); } } } removeSpaces (str); return str; }
/**Funcão interpretar*/ int interpretar(string linha){ istringstream ss(linha); string token; int cont = 0; vector<string> playerInfoVector; while (std::getline(ss, token, ' ')) { token = removeSpaces(token); if (token.compare("") != 0){ playerInfoVector.push_back(token); cont++; } } // Comando gerar if (playerInfoVector.at(0).compare("gerador") == 0 && cont != 0){ return gerador(playerInfoVector); } else if (playerInfoVector.at(0).compare("desenhar") == 0 && cont != 0){ return gerar_cena(playerInfoVector); } else if (playerInfoVector.at(0).compare("help") == 0 && cont != 0){ cout << MESSAGE_HELP; } else if (playerInfoVector.at(0).compare("exit") == 0 && cont != 0){ return 0; } else { // Como o comando invocado não é nenhum dos anteriores, devolve o erro correspondente cout << ERROR_COMMAND_NO_EXISTS; return -1; } }
main(){ char xx[] = "DOD stands for hello. this isn't for fun"; //printf("Original array: %s\n", xx); removeSpaces(xx); removePunctuation(xx); findPalindrome(xx); //printf("Redone array: %s\n", xx); }
void prepStr(char *str){ int j = 0; int size = (int)strlen(str); for(j=0; j < size; j++){ str[j] = (char)tolower(str[j]); } removeSpaces(str); }
/** * @brief Function that stores the parsed toked elements * * @param _line */ void MeshFileParser::saveTokenElements(QString _line) { QStringList _values = _line.split("="); if ((!_values.isEmpty()) && (_values.size() == 2)) { // Key_name = name of the variable, and the value is Marker_tag _currentParsedValues.insert(QString::number(_id), removeSpaces(_values.at(1))); _id++; } }
int main(int argc, char *argv[]) { //block of code for debugging purposes #if DEBUG fprintf(stdout, "%s\n%s\n%s\n", argv[1], argv[2], argv[3]); #endif if(myStrcmp(argv[1], "removeSpaces") == 0) { fprintf(stdout, "Change to: %s\n", removeSpaces(argv[2])); } else if(myStrcmp(argv[1], "switchCases") == 0) { fprintf(stdout, "Change to: %s\n", switchCases(argv[2])); }
int main() { char str[] = "Archana is a good girl"; removeSpaces(str); for(int i = 0; i < strlen(str); i++) { printf("%c", str[i]); } return 0; }
void WLineEdit::setFormData(const FormData& formData) { // if the value was updated through the API, then ignore the update from // the browser, this happens when an action generated multiple events, // and we do not want to revert the changes made through the API if (flags_.test(BIT_CONTENT_CHANGED) || isReadOnly()) return; if (!Utils::isEmpty(formData.values)) { const std::string& value = formData.values[0]; displayContent_ = inputText(WT_USTRING::fromUTF8(value, true)); content_ = removeSpaces(displayContent_); } }
int main(int ac, char**av) { if (ac == 2) { std::string s = removeSpaces(av[1]); if (checkSyntax(s.c_str())) find_parenthesis(s); else std::cout << "syntax error" << std::endl; } else std::cout << "argument error" << std::endl; return 0; }
bool isNumber(const char *s) { string str(s); // Remove leading and ending spaces str = removeSpaces(str); // No meaningful part if (str == "") return false; // More than one meaningful part if (str.find_first_of(' ') != string::npos) return false; unsigned pos; // Scientific notation if ((pos = str.find_first_of('e')) != string::npos) { // Check the second part if (isValidInteger(str.substr(pos + 1), true, false)) { // Check the first part str = str.substr(0, pos); // The first part of scientific notation can be decimal. if ((pos = str.find_first_of('.')) != string::npos) { // The second part of decimal is empty. if (pos == str.length() - 1) { return isValidInteger(str.substr(0, pos), true, false); } else { return isValidInteger(str.substr(0, pos), true, true) && isValidInteger(str.substr(pos + 1), false, false); } } else { return isValidInteger(str, true, false); } } else { return false; } } // Decimal if ((pos = str.find_first_of('.')) != string::npos) { // The second part of decimal is empty. if (pos == str.length() - 1) { return isValidInteger(str.substr(0, pos), true, false); } else { return isValidInteger(str.substr(0, pos), true, true) && isValidInteger(str.substr(pos + 1), false, false); } } // Integer if (isValidInteger(str, true, false)) return true; return false; }
//------------------------------------------------------------------------------ QString getParamInfo(QString *inputstr, QString param) { QString str = *inputstr; QString remove = "<meta name=\"" + param + "\" content=\""; str.remove(remove) .remove("\">"); str = removeSpaces(str); if (str == "RU") str = "rus"; if (str == "En") str = "eng"; return str; }
/** * Standard input for a training set * Parameter: _is The input stream * Parameter: _ts The training set to be read * @exception runtime_error If there are problems with the stream */ void ClassicTrainingVectors::readSelf(std::istream& _is) { #ifndef _NO_EXCEPTION try { #endif clear(); std::string line; // Determines the number of rows and columns in the training set long dim, size; _is >> dim; _is >> line; if (!sscanf(line.c_str(), "%ld", &size)) { int x, y; _is >> x; _is >> y; size = x * y; } getline(_is, line); theItems.resize(size); theTargets.resize(size); for (int i = 0; i < size; i++) { std::vector<floatFeature> v; v.resize(dim); for (int j = 0; j < dim; j++) { floatFeature var; _is >> var; v[j] = var; } getline(_is, line); theItems[i] = v; theTargets[i] = removeSpaces(line); } #ifndef _NO_EXCEPTION }
void WLineEdit::setText(const WT_USTRING& text) { WT_USTRING newDisplayText = inputText(text); WT_USTRING newText = removeSpaces(newDisplayText); if (maskChanged_ || content_ != newText || displayContent_ != newDisplayText) { content_ = newText; displayContent_ = newDisplayText; if (isRendered() && !inputMask_.empty()) { doJavaScript("jQuery.data(" + jsRef() + ", 'lobj')" ".setValue(" + WWebWidget::jsStringLiteral(newDisplayText) + ");"); } flags_.set(BIT_CONTENT_CHANGED); repaint(); validate(); applyEmptyText(); } }
// Description // // Extracts the Authy ID from the configuration file // // Parameters // // pszConfFilename - Full path to the configuration file // pszUsername - The Username (login) for which we are getting the Authy ID // pszCommonName - Common name from the OpenVPN certificate // // Returns // // standard RESULT // RESULT getAuthyIdAndValidateCommonName(__out char *pszAuthyId, const char *pszConfFilename, const char *pszUsername, const char *pszCommonName) { FILE *fpConfFile = NULL; char *pch = NULL; RESULT r = FAIL; char line[LINE_LENGTH]; char *columns[3] = {NULL}; int i = 0; if(!pszConfFilename || !pszUsername || FAILED(checkUsername(pszUsername))) { r = FAIL; trace(ERROR, __LINE__, "[Authy] getAuthyId: Wrong configuration file or username\n"); goto EXIT; } fpConfFile = fopen(pszConfFilename, "r"); if(NULL == fpConfFile) { trace(ERROR, __LINE__, "[Authy] getAuthyId: unable to read file %s\n", pszConfFilename); r = FAIL; goto EXIT; } memset(columns, 0, sizeof(columns)); while(NULL != fgets(line, ARRAY_SIZE(line), fpConfFile)){ pch = strtok(line," \t"); i = 0; while(pch != NULL && i < 3){ columns[i] = removeSpaces(pch); pch = strtok (NULL, " \t"); //Go to the next token i++; } if(columns[1] != NULL && 0 == strcmp(columns[0], pszUsername)){ trace(DEBUG, __LINE__, "[Authy] Found column for pszUsername=%s column is %s\n", pszUsername, line); break; } memset(columns, 0, sizeof(columns)); } if(columns[0] == NULL){ r = FAIL; trace(ERROR, __LINE__, "[Authy] Username %s not found in Authy Config file\n", pszUsername); goto EXIT; } assert(columns[1] != NULL); if(FALSE == isAnAuthyId(columns[1])){ r = FAIL; trace(ERROR, __LINE__, "[Authy] AuthyID %s for Username %s is not valid. Authy ID's can only be numeric values\n", columns[1], pszUsername); goto EXIT; } if(columns[2] != NULL && strcmp(columns[2], pszCommonName) != 0){ r = FAIL; trace(ERROR, __LINE__, "[Authy] CommonName %s does not match the configuration file common name %s\n", pszCommonName, columns[2]); goto EXIT; } snprintf(pszAuthyId, MAX_AUTHY_ID_LENGTH, "%s", columns[1]); trace(INFO, __LINE__, "[Authy] Found Authy ID: %s for username: %s\n", pszAuthyId, pszUsername); r = OK; EXIT: if(fpConfFile){ fclose(fpConfFile); } return r; }
// Prepare the parser by removing the whitespaces from the equation and setting the lookahead to 0 Parser(std::string e):equation(e), lookAhead(0), numOpenParen(0){ removeSpaces(equation); }
int main() { /*char c;*/ int choice; int n; char str[] = "gee ks f or g ee ks "; char path[128]; char S[128], T[128]; char *pattern = "-20"; char str1[32], str2[32]; char **s; /*do {*/ printf("MENU OPTIONS\n"); printf("1 -- remove spaces from string\n"); printf("2-- Check if a given sequence of moves for a robot is circular or not\n"); printf("3 -- Regex matching problem\n"); printf("4 -- Palindrome detection with non-alphanumeric characters\n"); printf("5 -- Normalize the path\n"); printf("6 -- replace space by percentage20 in a string\n"); printf("7 -- minimum window substring\n"); printf("8 -- integer to english words\n"); printf("9 -- restore IP addresses\n"); printf("10 -- check if strings are isomorphic\n"); printf("11 -- function to determine if a string is a valid number without using any built-in function\n"); printf("12 -- reverse string\n"); printf("13 -- reverse words in a sentence\n"); printf("14 -- shortest distance between words\n"); printf("15 -- shortest distance between words\n"); printf("\n"); printf("Enter your choice\n"); scanf("%d",&choice); switch(choice){ case 1: removeSpaces(str); printf("%s", str); break; case 2: printf("Enter path\n"); scanf("%s", path); printf("path is circular: %s", checkCircularpath(path)?"yes":"no"); break; case 4: palindrome(); break; case 5: printf("Enter path\n"); fgets(path, 128, stdin); printf("Normalized path: %s\n", normalize(path)); break; case 6: memset(path, '\0', 128); printf("Enter string\n"); scanf("%s", path); /*gets(path);*/ replace_spaces(path, pattern); printf("%s\n", path); break; case 7: printf("Enter the string\n"); scanf("%s", S); printf("Enter the pattern\n"); scanf("%s", T); min_window_substring(S, T); break; case 8: /*interger_to_english_words();*/ break; case 9: restore_ip_address(); break; case 10: printf("Enter strings of equal length\n"); printf("Enter string 1\n"); scanf("%s", S); printf("Enter string 2\n"); scanf("%s", T); printf("Strings are isomorphic : %s\n", isomorphic_strings(S, T)?"Yes":"No"); break; case 11: printf("Enter the string\n"); scanf(" %[^\n]s", S); //reading a space through scanf /*fgets(stdin, S, sizeof(S));*/ printf("Is number : %s\n", is_valid_number(S)?"yes":"no"); break; case 12: printf("Enter the string\n"); scanf(" %[^\n]s", S); //make scanf work with spaces //make scanf work with spaces reverse_string(S, strlen(S)); print_string(S, strlen(S)); break; case 13: printf("Enter the sentence\n"); scanf(" %[^\n]s", S); //make scanf work with spaces //make scanf work with spaces /*fgets(S, 128, stdin);*/ reverse_words(S); print_string(S, strlen(S)); break; case 14: printf("Enter number of words\n"); scanf("%d", &n); s = create_2Dchar_array(n, 128); input_2Dchar_array(s, n, 128); printf("enter word 1\n"); scanf("%s", str1); printf("enter word 2\n"); scanf("%s", str2); printf("Shortest distance between %s and %s : %d\n", str1, str2, shortest_distance(s, n, str1, str2)); break; default: printf("Invalid option\n"); break; } printf("\n\n"); /*}while((c=getchar())!='q'); */ return 0; }
int main(int argc, char* argv[]) { Heap heap = Heap(10); char c; Node *chars = NULL; Node *ptr = chars; /////////////////////////////// Read and Create Linked List (for Frequencies) //////////////////////////////// std::ifstream in(argv[1]); while (in.get(c)) { std::cout << c; if (chars == NULL) { Node *temp = new Node; temp->content = c; temp->label = "L:"; temp->label += static_cast<std::ostringstream*>(&(std::ostringstream() << (int) c)) -> str(); // Get ASCII Value temp->priority = 1; temp->next = NULL; temp->right = NULL; temp->left = NULL; chars = temp; ptr = temp; } else { Node *temp = find(chars, c); if (temp != NULL) { temp->priority++; } else { temp = new Node; temp->content = c; temp->label = "L:"; temp->label += static_cast<std::ostringstream*>(&(std::ostringstream() << (int)c))->str(); // Get ASCII Value temp->priority = 1; temp->next = NULL; temp->right = NULL; temp->left = NULL; ptr->next = temp; ptr = temp; } } } in.close(); ///////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////// Create Initial Heap ////////////////////////////////////// ptr = chars; while (ptr != NULL) { heap.insert(ptr); ptr = ptr->next; } int totalChars = heap.count(); ///////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////// Create Huffman Code Tree ///////////////////////////////// int counter = 0; Node *parent = NULL; while (heap.count() > 1) { Node *n1 = heap.removeMin(); Node *n2 = heap.removeMin(); parent = new Node; parent->label = "I:" + static_cast<std::ostringstream*>(&(std::ostringstream() << counter++))->str(); parent->content = '*'; parent->left = n1; parent->right = n2; parent->next = NULL; parent->priority = n1->priority + n2->priority; heap.insert(parent); } Node *codeTree = parent; ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////// Get Traversals //////////////////////////////////////////// std::ofstream outTree("tree.txt"); outTree << removeSpaces(preorder(codeTree)) << std::endl; outTree << removeSpaces(inorder(codeTree)) << std::endl; outTree.close(); ///////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////// Create Encoding Table //////////////////////////////////// Table *codeTable = new Table[totalChars]; std::string code = ""; generateEncodingTable(codeTree, codeTable, code); //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////// Write Code //////////////////////////////////////////////// std::ofstream outCode("code.txt"); in.open(argv[1]); c = '\0'; while (in.get(c)) { for (int i = 0; i < totalChars; i++) { if (c == codeTable[i].content) { outCode << codeTable[i].encoding; break; } } } in.close(); outCode.close(); //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////// Output Lengths //////////////////////////////////////// std::ofstream outLength("length.txt"); for (int i = 0; i < totalChars; i++) { outLength << (int) codeTable[i].content << " " << codeTable[i].encoding.length() << std::endl; } outLength.close(); //////////////////////////////////////////////////////////////////////////////////////// return 0; }
/// <summary> /// Evaluate_exps evaluates the specified expression. /// </summary> /// <param name="exp">The expression.</param> /// <returns>The evaluated result</returns> struct Result evaluate_expr(char* exp) { static const char* ods = "0123456789("; static const char* ops = "+-*/_"; // '_' is unary '-' struct Stack operands; struct Stack operators; Stack_Init(&operators); Stack_Init(&operands); removeSpaces(exp); findUnaryOperators(exp); //syslog(LOG_INFO, "parsing: %s", exp); int i; i = 0; while (exp[i] != '\0') { char c = exp[i++]; if (strchr(ods, c) != NULL) { // if char == operand if (c == '(') { Stack_Push(&operators, c); } else { int iStart = i - 1; int iEnd = iStart; do { c = exp[i++]; } while (c != '\n' && isdigit(c)); iEnd = --i; char num[MAX_DIGITS] = ""; strncat(num, exp + iStart, iEnd - iStart); Stack_Push(&operands, atoi(num)); } } else if (strchr(ops, c) != NULL) { // if char == operator int currentPres = getPrecendence(c); while (Stack_Size(&operators) > 0 && Stack_Size(&operands) > 0 && currentPres < getPrecendence((char)Stack_Top(&operators))) { if (evaluate_next_operator(&operands, &operators) == DIVIDED_BY_0) { return inf; } } Stack_Push(&operators, c); } else if (c == ')') { while (Stack_Top(&operators) != '(') { if (evaluate_next_operator(&operands, &operators) == DIVIDED_BY_0) { return inf; } } Stack_Pop(&operators); } } while (Stack_Size(&operators) > 0) { if (evaluate_next_operator(&operands, &operators) == DIVIDED_BY_0) { return inf; } } int resultInt = Stack_Top(&operands); syslog(LOG_INFO, "Result: %d", resultInt); struct Result result = {resultInt, false}; return result; }
int runCoreDetector( const SystemParameters& settings ) { // Retrieve some contents from input string inputDir = settings.InputDirectory; string inputFile = settings.InputFilename; string outputDir = settings.OutputDirectory; string outputFile = settings.OutputFilename; // Compile a vector of all files to process with related info vector<string> inputFilenames; // filenames (full or relative path) vector<string> inputClassifiers; // corresponding classifier keys vector<float> inputPitch; // input pitches, if used vector<float> inputAltitudes; // input altitudes, if used vector<float> inputRoll; // input rolls, if used vector<string> subdirsToCreate; // subdirs we may be going to create vector<string> outputFilenames; // corresponding output filenames if enabled // GT file contents if required string GTfilename = inputDir + inputFile; GTEntryList* GTs = NULL; // Process directory mode if( settings.IsInputDirectory || settings.IsTrainingMode ) { // Get a list of all files and sub directories in the input dir listAllFile( inputDir, inputFilenames, subdirsToCreate ); // Remove files that don't have an image extension (jpg/tif) cullNonImages( inputFilenames ); // Initialize classifier array inputClassifiers.resize( inputFilenames.size(), settings.ClassifierToUse ); } // If we're in process list mode else if( !settings.IsTrainingMode ) { // Read input list string list_fn = inputDir + inputFile; ifstream input( list_fn.c_str() ); // Check to make sure list is open if( !input ) { cerr << endl << "CRITICAL ERROR: " << "Unable to open input list!" << endl; return 0; } // Iterate through list while( !input.eof() ) { string inputFile, classifierKey; float alt, pitch, roll; // Metadata is in the input files if( settings.IsMetadataInImage ) { input >> inputFile >> classifierKey; removeSpaces( inputFile ); removeSpaces( classifierKey ); if( inputFile.size() > 0 && classifierKey.size() > 0 ) { inputFilenames.push_back( inputFile ); inputClassifiers.push_back( classifierKey ); } } // Metadata is in the list else {
/* You need to read the configuration file and extract the page size and number of pages * (these two parameter together define the maximum main memory you can use). * Values are in number of bytes. * You should read the names of the tables from the configuration file. * You can assume that the table data exists in a file named <table_name>.csv at the path * pointed by the config parameter PATH_FOR_DATA. ***************************************************************************************/ void DBSystem::readConfig(string configFilePath) { FILE *fd=fopen(configFilePath.c_str(),"rw+"); int count=0; char* temp=new char[100]; bool isBegin=false; bool isInTable=false; if(fd==NULL) cout<<"Config file not found"<<endl; fscanf (fd, "%s %d", temp, &pageSize); fscanf (fd, "%s %d", temp, &(numberOfPages)); fscanf (fd, "%s %s", temp, (pathForData)); fclose(fd); string sLine=""; ifstream infile; infile.open(configFilePath.c_str()); getline(infile, sLine); getline(infile, sLine); getline(infile, sLine); //cout<<sLine; //cout<<"Page size is : "<< pageSize << endl; //cout<<"Number of pages are : "<< numberOfPages <<endl; //cout<<"Path for table files is : "<< pathForData <<endl; string currentTableName; while(!infile.eof()) { string current(""); getline(infile, current); //cout << current<<endl; if( current.find("BEGIN") != -1 && !isBegin) { count=0; isBegin=true; continue; } else if( current.find("END") != -1 ) { if(count++==1) break; isBegin=false; isInTable=false; continue; } if(isBegin) { isInTable=true; isBegin=false; tableNames.push_back(current.substr(0,current.length())); currentTableName=current; tableNameToPrimaryKeys[currentTableName]=""; } else if(isInTable) { int index=current.find(','); string currentColumnName=current.substr(0,index); int len=current.length(); string currentDataType=current.substr(index+1,len); // cout<<currentDataType<<endl; currentColumnName=removeSpaces(currentColumnName); currentDataType=removeSpaces(currentDataType); if(currentDataType.find("varchar")!=string::npos || currentDataType.find("VARCHAR")!=string::npos) currentDataType="VARCHAR"; if(currentDataType=="integer") currentDataType="INT"; if(currentDataType=="float") currentDataType="FLOAT"; if(currentColumnName.compare("PRIMARY_KEY")==0){ // cout<<currentTableName<<" "<<currentDataType<<endl; tableNameToPrimaryKeys[currentTableName]=currentDataType; } else{ std::pair < string,string > bar = std::make_pair (currentColumnName,currentDataType); tableNameToColumnNames[currentTableName].push_back(bar); } } } }
void processLine(char* line){ int index; index = 0; char holder[30]; int i; for (i = 0; i < 30; i++){ holder[i] = '\0';} removeSpaces(line); if(line[0] == '{'){ index++; while(line[index] != ',') { holder[index-1] = line[index]; index++; } if(head == NULL){ createList(holder); } else{ addToList(holder); } //printf("%s", curr->name); } while(line[index] != '\0'){ //skip comma if(line[index] == ','){ index++; } //skip else if(line[index] == '['){ index++; } else if(line[index] == '('){ index++; char xBuffer[100]; for (i=0; i<100;++i) {xBuffer[i]='\0';} int size; size = 0; //x value while(line[index] != ','){ xBuffer[size] = line[index]; index++; size++; } double xPoint=(atof(xBuffer)); curr->p.points[curr->p.size].x= xPoint; index++; char yBuffer[100]; for (i=0; i<100;++i) {yBuffer[i]='\0';} size = 0; //y value while(line[index] != ')'){ yBuffer[size] = line[index]; index++; size++; } double yPoint=(atof(yBuffer)); curr->p.points[curr->p.size].y= yPoint; curr->p.size++; //printf("%s\n", curr->name); //printf("(%lf, %lf)\n", curr->p.points[0].x, curr->p.points[0].y); } else{ index++; } } // printf("%s", line); }
/*@@ @routine ParseFile @author Paul Walker @desc This routine actually parses the parameter file. The syntax we allow is <ul> <li>a = b <li>a,b,c = d,e,f <li># rest of the line is ignored <li>x = "string value" </ul> So it is easy to parse <p> We go through the file looking for stuff and then set it in the global database using calls to the passed in set_function. @enddesc @history @hdate Tue Jan 12 16:41:36 1999 @hauthor Tom Goodale @hdesc Moved to CCTK. Changed to pass data to arbitrary function. Changed to take a file descriptor rather than a filename. @endhistory @var ifp @vdesc The filestream to parse @vtype FILE * @vio in @vcomment @endvar @var set_function @vdesc The function to call to set the value of a parameter @vtype int (*)(const char *, const char *) @vio in @vcomment @endvar @var ConfigData @vdesc Flesh configuration data @vtype tFleshConfig * @vio in @vcomment @endvar @returntype int @returndesc 0 - success @endreturndesc @@*/ int ParseFile(FILE *ifp, int (*set_function)(const char *, const char *, int), tFleshConfig *ConfigData) { /* Buffers for parsing from the file */ char *tokens, *value; char *subtoken, *subvalue; /* Positions in the buffers */ int ntokens; /* Status flags */ int intoken, inval; /* Current char. Have to make it an int so we can compare with EOF. See man 3 fgetc */ int c; int num_errors; /* number of errors in file parsing */ num_errors = 0; /* avoid compiler warning about unused parameter */ ConfigData = ConfigData; /* allocate parse buffers */ tokens = (char *) malloc (4 * BUF_SZ); value = tokens + 1*BUF_SZ; subtoken = tokens + 2*BUF_SZ; subvalue = tokens + 3*BUF_SZ; intoken = 0; inval = 0; while ((c=fgetc(ifp)) != EOF) { #ifdef DEBUG printf("%c",c); #endif /* Main Loop */ while (c == '#' || c == '!' ) { /* Comment line. So forget rest of line */ while ((c=fgetc(ifp)) != '\n' && c != EOF) { #ifdef DEBUG printf("%c",c); #endif } if (c == '\n') { lineno++; } c = fgetc(ifp); #ifdef DEBUG printf("%c",c); #endif } /* End of line */ if (c == '\n') { if(intoken) { fprintf(stderr, "Parse error at line %d. No value supplied.\n", lineno); num_errors++; intoken = 0; } #ifdef DEBUG printf ("LINE %d\n",lineno); #endif lineno ++; } /* Token character */ if (intoken && c != '=') { tokens[intoken++] = c; CheckBuf(intoken,lineno); } /* Start of a new token */ if (c != ' ' && c != '\t' && c != '\n' && !inval && !intoken) { intoken = 0; tokens[intoken++] = c; } /* End of a token signified by an = */ if (c == '=') { if (intoken) { unsigned int ll; tokens[intoken] = '\0'; /* Very important! */ intoken = 0; inval = 0; removeSpaces(tokens); ntokens = 1; for (ll=0;ll < strlen(tokens); ll++) if (tokens[ll] == ',') ntokens++; #ifdef DEBUG printf ("\nNew token! >>%s<<\n",tokens); printf ("%d token elements\n",ntokens); #endif /* Scan ahead to the beginning of the value * and check if the value is a string or not. * This parser DOES strip quotes off of the strings. */ while ((c = fgetc(ifp)) == ' ' || c == '\n' || c == '\t') { #ifdef DEBUG printf("%c",c); #endif if (c == '\n') { #ifdef DEBUG printf ("LINE %d\n",lineno); #endif lineno++; } } if (c == '"') { /* Just handle the thing. */ int p = 0; if (ntokens > 1) { fprintf (stderr, "%s%s%s\n", "WARNING: Multiple string ", "tokens not supported for ", tokens); fprintf(stderr, "This is a fatal error"); /* deallocate parse buffers */ free (tokens); return 1; } while ((c = fgetc(ifp)) != '"') { #ifdef DEBUG printf("%c",c); #endif /* Make an important decision NOT to include * line feeds in the string parameters */ if (c != '\n') value[p++] = c; if (c == '\n') { printf ("%sWarning:%s Quoted string contains newline for token %s\n", BOLDON, BOLDOFF, tokens); printf ("This could indicated a parameter file error or missing quote\n"); #ifdef DEBUG printf ("LINE %d\n",lineno); #endif lineno++; } CheckBuf(p,lineno); } value[p] = '\0'; #ifdef DEBUG printf ("\nString %s -> %s\n", tokens,value); #endif set_function(tokens,value, lineno); } else if (c == '$') { /* We got a define */ /* FIXME: Assume it is a parameter file for now */ char filename[500]; char *dir; char *file; int lpar; CCTK_ParameterFilename(500,filename); Util_SplitFilename(&dir,&file,filename); lpar=((strlen(file)-3)*sizeof(char)); /* ignore everything else on the line */ while (!(c==' ' || c=='\t' || c == '\n' || c == EOF)) { c = fgetc(ifp); #ifdef DEBUG printf("%c",c); #endif } strncpy(value,file,lpar); free(dir); free(file); value[strlen(value)-1] = '\0'; set_function(tokens,value,lineno); } else { int p = 0; value[p++] = c; if (ntokens == 1) { /* Simple case. We have an int or a double which contain no spaces! */ c = fgetc(ifp); #ifdef DEBUG printf("%c",c); #endif while (!(c==' ' || c=='\t' || c == '\n' || c == EOF)) { value[p++] = c; CheckBuf(p,lineno); c = fgetc(ifp); #ifdef DEBUG printf("%c",c); #endif } value[p] = '\0'; #ifdef DEBUG printf ("Parsed %d characters\n", p); printf("\nFloat/Int: %s -> %s\n", tokens,value); #endif set_function(tokens,value,lineno); if (c=='\n') { #ifdef DEBUG printf ("LINE %d\n",lineno); #endif lineno++; } } else { /* Harder case of multiple tokens */ int ncommas = 0; int pp=0, i; int pt, pv; value[pp++] = c; /* OK, since we only have numbers in the old input stream, we can go along getting ntokens-1 commas, stripping spaces, and make a nice little string. */ c = fgetc(ifp); #ifdef DEBUG printf("%c",c); #endif while (ncommas < ntokens-1 && c != EOF) { if (!(c == ' ' || c == '\t' || c == '\n')) { value[pp++] = c; CheckBuf(pp,lineno); } if (c == ',') ncommas ++; c = fgetc(ifp); #ifdef DEBUG printf("%c",c); #endif } if (c == ' ' || c == '\t') { /* Great now strip out the spaces */ while((c = fgetc(ifp)) == ' ' || c=='\t' || c == '\n') { #ifdef DEBUG printf("%c",c); #endif if (c=='\n') { #ifdef DEBUG printf ("LINE %d\n",lineno); #endif lineno++; } } } /* And tack the rest on */ value[pp++] = c; CheckBuf(p,lineno); c = fgetc(ifp); #ifdef DEBUG printf("%c",c); #endif while (c != ' ' && c != '\t' && c != '\n' && c != EOF) { value[pp++] = c; CheckBuf(pp,lineno); c = fgetc(ifp); #ifdef DEBUG printf("%c",c); #endif } value[pp] = '\0'; #ifdef DEBUG printf("Comma list: %s -> %s\n", tokens,value); #endif /* So parse out the tokens */ pt = 0; pv = 0; for (i=0;i<ncommas;i++) { pp = 0; while (tokens[pt] != ',') { subtoken[pp++] = tokens[pt++]; CheckBuf(p,lineno); } subtoken[pp] = '\0'; pp = 0; while (value[pv] != ',') { subvalue[pp++] = value[pv++]; CheckBuf(pp,lineno); } subvalue[pp] = '\0'; set_function(subtoken,subvalue,lineno); #ifdef DEBUG printf("Setting sub-token %s -> %s\n", subtoken, subvalue); #endif /* Now remember we are sitting on a comma * in both our input strings, so bump by one */ pv ++; pt ++; } /* And OK, so now we have one parameter left * so lets handle that */ pp = 0; while (tokens[pt] != '\0') { subtoken[pp++] = tokens[pt++]; CheckBuf(pp,lineno); } subtoken[pp] = '\0'; pp = 0; while (value[pv] != '\0') { subvalue[pp++] = value[pv++]; CheckBuf(pp,lineno); } subvalue[pp] = '\0'; set_function(subtoken,subvalue,lineno); } } } else { fprintf (stderr, "Parser failed at = on line %d\n", lineno); } } } /* deallocate parse buffers */ free (tokens); return num_errors; }