Finally the server accepts the data sent by my client. Here is the solution: - encode the original string to UTF8 and append it with "\r\n". - open network stream. - and simply send it without using any writer. Nevertheless I thank to you all trying to help me by...
You have undefined behavior because you return a pointer to a local variable. The array c in the add function will go out of scope once the function returns, leaving you with a stray pointer.
You are wrong. The result of these two code snippets char line[80] = "1:2"; and char line[80]; strcpy( line, "1:2" ); is the same. That is this statement char line[80] = "1:2"; does work.:) There is only one difference. When the array is initialized by the string literal all elements...
In c a string is a pointer to some block of memory each byte of which contains a character. Say I have the following code: char * helloString = "hello" Once this has run all that is stored in helloString is the position in memory of the character 'h'. The...
c,arrays,pointers,recursion,c-strings
Actually &str[1] is same as str + 1. Thus, function count() is called recursively, receiving as second argument a pointer to the next char in the string, until it meets NULL. The rest of its functionality is pretty obvious. It counts how many times ch (the char passed as the...
Since you know that C uses ASCII, you could create your own function: bool upper(char chr) { return chr >= 'A' && chr <= 'Z'; // same as return chr >= 65 && chr <= 90 } ...
c++,c,string,optimization,c-strings
If you want speed, don't create a string just in order to do a comparison; especially, don't create six strings since you might sometimes only need one or two of them. It's not relevant whether they are C strings or C++ strings. Do you know how long X1, X2 and...
You cannot use functions that uses the null as a string terminator: int k = send(dataSock, body.c_str(), strlen(body.c_str()), 0); You're using strlen above. This is not correct. The fix for this is to use the length() function for std::string: int k = send(dataSock, body.c_str(), body.length()), 0); You make the same...
The error is here: if ( string[j] != string [k-j] ){ The second character should be string[k-j-1]. For instance, when j = 0, you should compare with string[k-1] to compare the first and last characters of the string. Also, you have a memory leak. At the bottom of the outer...
I used Turbo C (even not ++) but it was long long time ago ... More seriously, I assume : cnic is a char array of size 13 (12 + terminating null) cnic2 should be a 2D array of 100 char arrays of size 13 (it is not what is...
struct classcomp { bool operator() (const int& lhs, const int& rhs) const {return lhs<rhs;} }; Defines a functor by overloading the function call operator. To use a function you can do: int main() { std::set <wrap, bool (*)(wrap,wrap)> myset(compare); return 0; } Another alternative is to define the operator as...
You have a typo, but interestingly the code is compiling for sure int length = strlen(response->file_content + MAX_HEADER_LENGTH ); it should be int length = strlen(response->file_content) + MAX_HEADER_LENGTH; the reason why the code is compiling is because what this means response->file_content + MAX_HEADER_LENGTH is pass the response->file_content pointer incremented by...
c++,format,long-integer,c-strings
If this is MFC, it should be like this: CString cstr; cstr.Format("SELECT 123=%ld, 456=%ld AND type = '%s' ", 123, 456, "'type'"); It's like printf. ...
c++,boost,template-meta-programming,c-strings,boost-test
I don't think you can really support this scenario because all SFINAE techniques I can think of would run into ambiguous overloads. This is, in fact, precisely the documented limitation with Boost's has_equal_to<A,B,R> type trait: There is an issue if the operator exists only for type A and B is...
The scanf family of functions are good for simple parsing, but not for more complicated things like you seem to do. You could probably solve it by using e.g. strstr to find the comment starter "//", terminate the string there, and then remove trailing space....
c++,c,c++builder,c-strings,c++builder-xe6
You probably mix including cstring and string.h. Do not do this. The former declares: void * memchr(void *, int, size_t); the latter does void * memchr(const void *, int, size_t); Those are not of the same type....
It is unclear what you intended to do, but the code does exactly what you told it to do. A C "string" is a series of char elements that ends with a null value. Whatever comes after that null value is not part of the string. Your string before the...
char tmpstr1[16]; char tmpstr2[16]; ... /* delimPtr = strstr(tempbuff,":"); endPtr = strstr(delimPtr,";"); strncpy(tmpstr1,tempbuff,delimPtr-tempbuff-1); strncpy(tmpstr2,delimPtr+2 ,endPtr-delimPtr-2); */ sscanf(tempbuff, "%15s : %15[^;];", tmpstr1, tmpstr2); ...
You are trying to cast away "constness": word points to constant data, but the result of static_cast<void*> is not a pointer to constant data. static_cast will not let you do that. You should use static_cast<const void*> instead....
var = (LPCTSTR)sqlString; // var is LPCTSTR type What are you doing with var later on? When sqlString loses scope, var points to garbage. This is no copying, var is just a pointer to the sqlString internal buffer. That said, use bind parameters. Do not use any kind of string...
c++,computer-science,c-strings,c-string
after the line with the j++; insert the following if (j < 201) { documentArray[i][j+1] = '\0'; # terminate the c string } else { documentArray[i][j] = '\0'; # cannot terminate the c string, overwrite the last char to terminate the string } But please make sure that every read...
c,string,dynamic-arrays,c-strings
string + x is an operation called Pointer Arithmetic. That way you are providing reference to a mathematically calculated memory area and by semantics it is equivalent to &string[x] What actually happens behind the calculation: (&string + (x * sizeof(*string))) which is why it is a very specific notion when...
c++,loops,c-strings,code-cleanup,character-arrays
Here a shorter version of your code. mainly I removed extra code when you check input by putting a do while so the case of wrong input the re-input go back to the first try. You also have a missing bracket in the last else, it cause you to re-enter...
c,segmentation-fault,malloc,coredump,c-strings
Below code should work: #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *str1 ; char *str2 ; char *str3; int l1,l2,l3; str1 = (char*)malloc(10); str2 = (char*)malloc(10); strcpy(str1,"United" ); strcpy(str2,"Front" ); l1 = strlen(str1)+1; l2 = strlen(str2)+1; l3 = l1 + l2; str3 = (char *)malloc(l3); str3 =...
msg = "This is a UDP test string! (packet %d)\n", ++pktcnt That is not how you put a formatted string into a variable in C. You need to use sprintf, and you need to make sure that adequate space is allocated in the string. For example char msg[200]; sprintf(msg, "This...
c++,pointers,dynamic-arrays,c-strings
This part doesn't do what you think it does: str1 = "This string"; add1 = " add this one"; You're attempting to assign a string literal ("This string") to a string pointer (str1). That won't work because: you've basically thrown away the pointers that you just allocated with new one...
You're not allocating enough space. if (!(mem = (char **)malloc(size + 1))) only allocates size+1 bytes. But you need to allocate space for size+1 pointers, and pointers are typically 4 bytes. You need to multiply the number of elements by the size of each element: if (!(mem = malloc((size +...
c++,char,ifstream,getline,c-strings
getline's return value is the istream object which I guess it's not something that you want to assign to localHouse->location. getline reads a line of your file into buffer variable that you have provided as the first parameter.
scanf(line, " %c", &ch) /* ^ */ The space before percent will cause scanf to ignore all whitespace characters (space, tab, newline) if present. i.e. condition if(ch == ' ') will be always false. In your question, this is not something that you like, so remove this whitespace. EDIT Also...
you need to init your strings, i.e., reserve a buffer you need to increment the dest pointer. #include <iostream> using namespace std; int main(){ int const STRING_SIZE=20; char userText[STRING_SIZE*2]=""; char justCharTxt[STRING_SIZE]=""; char * txtPt = justCharTxt; cout << "Enter text: " << endl; cin.getline(userText, STRING_SIZE); for (int i =...
c,string,string-length,c-strings
Now, I figure I can just stick the null terminal character in there and fix the problem (maybe that will cause errors further down the line), but I would prefer to know what's going on under the hood here. That's literally the solution. strlen is searching for a NULL...
It can be done as shown below: char str[20] = "22 3 43 5"; char *vec[4]; int i=0; char *p = strtok(str," "); while(p!= NULL ) { vec[i] = malloc(20); /* Free the memory once you are done using it */ strcpy(vec[i],p); p = strtok(NULL," "); i++; } If you...
c,arrays,string,file,c-strings
One problem I see is that you need to move the line if(currChar == '\n') currLine++; inside the while loop. I see a few more problems that I will be able to describe when I am on a full fledged computer, not a tablet. Update You have char * fileToArray(char...
After One Line After this loop for (int k = i; documentCopy[k] != '\0'; k++) { documentCopy[k] = documentCopy[k+1]; } i--; //Add This line in your Code. This will work. for example if you are checking a[0] and shifting a[0] = a[1] So you need to check a[0] again because...
You can use strrchr in Swift import Darwin let str = "4|0|66|5|0|3259744|6352141|1|3259744" func stringLastIndexOf(src:String, target:UnicodeScalar) -> Int? { let c = Int32(bitPattern: target.value) return src.withCString { s -> Int? in let pos = strrchr(s, c) return pos != nil ? pos - s : nil } } stringLastIndexOf(str, "|") //...
Here is a strtok() version of splitting the command: char** split(char *command, int* size) { char** ret; char* t; int i; for(i=0, t=strtok(command, " "); t!=NULL;++i ) { ret[i]=t; t = strtok(NULL, " "); } *size = i; return ret; } You can use it like this: char** args; int...
c,arrays,pointers,return-type,c-strings
First, allocate memory for strArray. Assuming, arrLen is an integral variable, not a pointer, char** strArray = malloc(arrLen*sizeof(*strArray)); if ( strArray == NULL ) { // Deal with error condition } Then, allocate memory for each element of the array. for ( i = 0; i < arrLen; ++i )...
char *a; Here, a is just a pointer of type char*. It points to some "random" location. There isn't any memory allocated to it. Writing to this invalid memory location invokes Undefined Behavior. You can write to this location only if Memory for a is allocated dynamically using malloc/calloc. a...
The standard C++ way would be to use a std::vector: std::vector<char> sockets::TCPSocket::doRecv(int flags) { std::vector<char> incomingDataBuffer(this->bufferSize); ssize_t bytesReceived = recv(this->filedes, &incomingDataBuffer[0], this->bufferSize, flags); // TODO set timeout - If no data arrives, // the program will just wait here until some data arrives. if (bytesReceived == 0 || bytesReceived ==...
c,arrays,computer-science,bubble-sort,c-strings
Arrays are not assignable as you're attempting in C. You need to setup some buffer swapping logic. For example. if(strcmp(str[j+1],str[j]) < 0) // note: fixed. { strcpy(temp, str[j]); strcpy(str[j], str[j+1]); strcpy(str[j+1], temp); } Other issues with your code: Incorrect size of your input array. All those strings require at least...
java,android,substring,c-strings
Try with String.substring(beginIndex, endIndex) String string = "11101204"; System.out.println(string.substring(0, 3)); System.out.println(string.substring(3, 5)); System.out.println(string.substring(5, 6)); System.out.println(string.substring(6, 8)); Output: 111 01 2 04 ...
Use Format method of CString class: CString sNum; long double fNum = 10.0; sNum.Format(_T("%f"), fNum); ...
c,string,visual-c++,string-concatenation,c-strings
The method in the answer you linked to: strcat() for formatted strings is safe against overlapping string issues, but of course it's unsafe in that it's performing unbounded writes using sprintf rather than snprintf. What's not safe, and what the text about overlapping strings is referring to, is something like:...
The variable process is already a pointer, &process has type char** and is a pointer to the pointer variable, not the pointer to the allocated buffer. sizeof(char) always equals 1 by definition, so is unnecessary in the malloc() call. If you use scanf() it should be thus: scanf( "%79s", process...
c,char,runtime,c-strings,dynamic-allocation
Since you are using scanf to read the count, I suppose that you will be using it to read the strings as well. If your C library is Posix 2008 compatible [Note 1], then you can use the m length modifier to a scanf %s %c or %[ format, which...
#include <stdio.h> int number_of_repeating(char *word,char k){ int b=0,len=0,i; gets(word); //<------- You need to remove this one because it may overwrite len=strlen(word); for(i=0;i<len;i++){ if(word[i]==k) b++; } return b; } int main(void) { // your code goes here printf("%d",number_of_repeating("johnny",'n')); return 0; } ...
strcpy copies the entire string. try strncpy. note you will need to add a null terminator to the end of the string. http://www.cplusplus.com/reference/cstring/strncpy/...
#include <stdio.h> int main(){ char buff[80]; int n; while(fgets(buff, sizeof(buff), stdin)){ sscanf(buff, " %n", &n); if(n && buff[n-1] == '\n')//only whitespaces line.(nothing first word) //putchar('\n');//output a newline. fputs(buff, stdout);//output as itself . else fputs(buff + n, stdout); } return 0; } ...
c,compiler-construction,compiler-optimization,c-strings,null-terminated
You can store the length of the allocation. And malloc implementations really do do that (or some do, at least). You can't reasonably store the length of whatever string is stored in the allocation, though, because the user can change the contents to their whim; it would be unreasonable to...
"Hello There" doesn't fit in a character array of size 10. This is good example of why you should not use gets. Use: fgets(string, sizeof(string), stdin); ...
c++,file,menu,fstream,c-strings
Your input processing is marred. I suggest something more along these lines: void loadData(ifstream &inFile, Task tasks[], int &listSize) { while (inFile.get(tasks[listSize].courseName, MAXCHAR, ';') && inFile.ignore(200, ';') && inFile.get(tasks[listSize].taskDescrip, MAXCHAR, ';') && inFile.ignore(200, ';') && inFile.get(tasks[listSize].dueDate, MAXCHAR, '\n')) { inFile.ignore(200, '\n'); listSize++; } inFile.close(); } Produces the following output: Welcome...
A string-delimiter function that uses strtok's prototype and mimicks its usage: char *strtokm(char *str, const char *delim) { static char *tok; static char *next; char *m; if (delim == NULL) return NULL; tok = (str) ? str : next; if (tok == NULL) return NULL; m = strstr(tok, delim); if...
c,pointers,c-strings,postfix-notation,infix-notation
The problem is that you process p_newStr without initializint it, and only performing pointer arithmetic on it. I guess, that you wanted to see it as a string, adding chars to it. So first initialisze it: char* p_newStr = newStr; // It was unitinitalised, pointing at random location Then note...
You don't mention how many objects you expect to have of your type, but I will assume that we are not talking about so many that you will be anywhere near exhausting your available address space. Just encapsulate a sufficiently large char_array (say 10 times the largest expected size) in...
The value of charstr gets destroyed at the end of the function before the caller assigns it to variable. You don't need a function, the caller can use CStringA directly and note that test is valid before sFilePathA goes out of scope. CStringA sFilePathA(filePath); const char *test = sFilePathA; ...
You are hitting what is considered to be undefined behavior. It's working now, but due to chance, not correctness. In your case, it's because the memory in your program is probably all zeroed out at the beginning. So even though your string is not terminated properly, it just so happens...
The simplest way I can think of is; std::vector<char> buffer; // some code that places data into buffer char *c = new char[buffer.size()]; std::copy(buffer.begin(), buffer.end(), c); // use c delete [] c; std::copy() is available in the standard header <algorithm>. This assumes the code that places data into buffer explicitly...
Point 1: Nested functions are not standard C. They are supported as GCC extension.. Point 2: printf("&b is:%s\n",&b); is wrong and invokes UB, because of improper format specifier. You need to change that to printf("&b is:%p\n",(void *)&b); Point 3: &(&a) is wrong. the operand for & needs to be...
c,pointers,struct,variable-assignment,c-strings
So yes, typical beginner's mistake. Thanks to @WhozCraig I figured I was doing this wrong. I shouldn't have dereferenced the pointer. I have so much to learn. Thanks for the help! //this works fine char * name = "John"; name = "Doe"; ...
delphi,access-violation,c-strings
StrPas(PAnsiChar('x')); I posit that 'x' is treated as a character literal rather than a string literal. And so the cast is not valid. If so then this will work as you would expect StrPas('x'); due to an implicit conversion. Or StrPas(PAnsiChar(AnsiString('x'))); thanks to the explicit conversion. I think the former...
this is the source of your problem: char *chPtr = new char[10]; // Create a char pointer type variable, and point it at the memory allocated for a char array of length 10 chPtr = "September"; first you allocate a heap memory on chPtr , then allocate a non-heap memory...
c,string,pointers,printf,c-strings
Let's examine it line by line: char *str = "Ninechars"; printf("Start\n"); printf("%s\n", str); printf("%p\n", str); // address of first char of str printf("%p\n", str+1); // address of second char of str The above addresses are part of the data segment of process' virtual memory. printf("%s\n", str[1]); Actually, str[1] == *(str...
First of all, the line char * f[e]; declares a variable-sized array of pointers to char. This is not valid standard C++, but using a compiler extension. It is not recommended to use such compiler extensions, as they make your code un-portable. Second, and most important, you are then trying...
c++,string,templates,c-strings
Instead of letting the type T be determined from the second parameter, utilize the builtin typedefs in vector to force T to be determined from the first parameter and force the type of the second parameter to be determined from the first: #include <iostream> #include <vector> #include <string> #include <algorithm>...