Menu
  • HOME
  • TAGS

Convert C# String to MFC CString in C# project?

c#,c++,string,mfc,c-strings

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...

Printf and Strcpy Bug in C language

c,printf,strcpy,c-strings

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.

difference between character array initialized with string literal and one using strcpy

c,pointers,token,c-strings

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...

input strings in c and how to store the string into variable

c,string,input,c-strings

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...

Progress of recursive functions on strings

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...

Check if character is upper case in older c-style

c++,string,c-strings

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 } ...

Optimization while mixing c style strings with c++ strings

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...

Convert tiff image into String to be posted as binary application/octet-stream (C++)

c++,http,post,c-strings

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...

Make a string Palindrome in C

c,palindrome,c-strings

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...

Comparing a String with 2d Array [closed]

c++,arrays,c-strings,turboc++

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...

How to create a set with my customized comparison in c++

c++,set,c-strings

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...

C strings building

c,sockets,c-strings

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...

Bug (??) in formatting long values with CString::Format

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. ...

Boost Test BOOST_CHECK_EQUAL with types convertible to array

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...

How to read string until two consecutive spaces?

c,format,sscanf,c-strings

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....

Conflicting types for 'memchr' [closed]

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....

strcpy adding random numbers to empty string

c,string,strcpy,c-strings

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...

reading input parameters from a text file with C

c,file-io,c-strings

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); ...

static_cast from 'const char *' to 'void *' is not allowed

c++,casting,c-strings

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....

CString to LPCTSTR conversion breaks sql query

c++,atl,c-strings

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...

Copy words from c-string into 2D array of c-strings

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 program Strings Example how come the result is 98?

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...

Is there a simpler way to loop for error checking and quitting? (C-strings/Character Arrays) [closed]

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...

Segmentation fault (core dumped) while performing strcat using pointers

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 =...

Format string error in C over network

c,udp,c-strings

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...

Modifying dynamic character arrays using pointers

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...

Manipulation of arrays of strings in C

c,arrays,c-strings

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 +...

ifstream no conversion from char to char exists error

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.

Reading different types in C from File

c,scanf,c-strings

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...

Remove/ignore everything except characters in a Cstring

c++,c-strings

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 =...

Why is the size of my string changing? (C)

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...

Split string with spaces to vector of strings in C

c,string,c-strings

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...

File to array of strings (line by line)

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...

cStrings Remove non-alpha/non-space character - C++

c++,c,cstring,c-strings

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...

Swift fast low level String lastIndexOf

string,swift,c-strings

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, "|") //...

How to split a C-String into an array of C-Strings

c++,strtok,argv,c-strings

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...

Mallocing Space for String Array in C

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 )...

Scan and Print a string

c,c-strings

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...

how do I delete allocated memory and still return its value from method

c++,dynamic-arrays,c-strings

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 ==...

How do I output a bubble sorted 2-D string array in C?

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 - How to split strings based on certain length ? [closed]

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 ...

Converting long double to CString

c++,mfc,c-strings,long-double

Use Format method of CString class: CString sNum; long double fNum = 10.0; sNum.Format(_T("%f"), fNum); ...

Is it safe safe to concatenate formatted strings using sprintf()?

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:...

User-input string into array, causing buffer overflow

c,arrays,user-input,c-strings

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...

Is it possible to allocate the correct amount of space to strings in C during run time?

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...

Count number of same letters in a string

c,string,c-strings

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

Chop up string into chunks of 512 bytes in c

c,c-strings

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/...

Program to remove preceding whitespace

c,arrays,c-strings

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

Can a C implementation use length-prefixed-strings “under the hood”?

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...

How to print duplicate letters in a string with their count number in C?

c,c-strings

"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); ...

fstream . Trouble printing all items in list

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...

Implementing `strtok` whose delimiter has more than one character

c,delimiter,strtok,c-strings

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...

Output shows un common characters while changing from infix to postfix notation using C++

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...

What's the fastest way to create a C-compatible unbounded string in Ada?

interface,ada,c-strings

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...

Converting form CString to const char*

c++,const,c-strings

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; ...

C character array and its length

c,c-strings

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...

Copy vector into char*

c++,vector,char,c-strings

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...

No More Confusing Pointers

c,arrays,pointers,c-strings

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 - understanding struct members vs pointers (char *)

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"; ...

Casting literals to PChar / PAnsiChar

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...

CStrings and pointers: Heap corruption when trying to delete a character array

c++,arrays,pointers,c-strings

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...

Playing with pointers, dazed and confused by char * strings

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...

c strings unable to display (and maybe input)

c++,c-strings

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...

is it possible to make template auto cast c-string to c++ string object?

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>...