w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
C++ memcpy to char* from c_str
Yes, this will work as long as your string in from is shorter than 20. Oh, no, wait, we are also copying the NULL terminator so it must be shorter than 19. I guess you see how that can lead to some confusion. Which is by the way exactly the reason why this code is dangerous: I am assuming this is demo code and your actual code will get that string from some sort of input. At that moment you will not be able to control how long it is. You can truncate it but you might forget to do that which means that your program will be copying content to memory that possibly does not belong to it. This might lead to a crash but at least to undefined behaviour as you are overwriting memory that might contain other important data. Using the string class actually helps to avoid such problems by not havin

Categories : C++

Why is memcpy from int to char not working?
Probably int is four bytes on your platform. ideone does show a warning, if there is also an error: http://ideone.com/TSmDk5 prog.cpp: In function ‘int main()’: prog.cpp:7:13: warning: overflow in implicit constant conversion [-Woverflow] prog.cpp:12:5: error: ‘error’ was not declared in this scope

Categories : C++

Using memcpy trying to copy one struct into a char[] buffer
You have no code to sensibly print the contents of the buffer, so you are expecting this to work by magic. The stream's operator << function expects a pointer to a C-style string, which the buffer isn't.

Categories : C++

cout << with char* argument prints string, not pointer value
You should change your code to this: cout << static_cast<const void*>(terry); The problem is that << operator is overloaded for pointers to C-style strings for printing the content of the string. If you cast it to the raw pointer instead, you will have the default behaviour of printing pointer using iostreams as you want.

Categories : C++

C++ std::cout and string printing in wrong order
If there is a carriage return at the end of the string it will move the position of output to the beginning of the console line when printed. #include <iostream> int main() { std::cout << "some line " << "." << std::endl; // ^^ carriage return }

Categories : C++

Checking if a char isn't equal to the first 6 letters of the alphabet
your condition is a bit wrong, u meant ((t >= 'g' && t <= 'z') || (t >= 'G' && t <= 'Z')) this condition say: t is bigger or equal 'g' and smaller or equal 'z' or t is bigger or equal 'g' and smaller or equal 'Z' your condition said t is smaller then 'a' or bigger then 'f' and t is smaller then 'A' or bigger then 'F' so every character, including numbers characters and signs could pass the condition also, when using an if statement with && and || use the "(" and ")" and explain which parts are seperated

Categories : Java

Using float char(as operator) float in a single cout line. C++
Although technically @tomriddle_1234 is correct you cant do a kind of scripting result, you can however to the calculation first and ensure you only have one line doing the output, something like: float result // this can also be implemented using switch if (op == '*') { result = first * last; } else if (op == '/') result = first / last; // continue for other operators if (op){ cout << first << op << last << "=" << result; } That will at least reduce repetition a bit more.

Categories : C++

C# console calling SQL - bad execution while string contains lithuanian letters
Are Lithuanian characters multibyte? (like Japanese for example) Is the GroupFilterName NVARCHAR or VARCHAR? If it's NVARCHAR, perhaps you need to put N in front of the string. Eg. readname.CommandText = "SELECT [ID] FROM [Net7].[dbo].[GroupFilter] WHERE [GroupFilterName]=N'" + CE_ParentName_ + "'"; And see asawyer's comment regarding avoiding injection attacks.

Categories : C#

MySQL, sort single letters first, then double letters, then triple letters
For the data you have provided, you can just use the length: order by length(letters), letters; This assumes that the letters are as described in the question, with no additional letters afterwards. If these are prefixes, the brute force approach would be: order by ((substring(letters, 1, 1) = substring(letters, 2, 1)) + (substring(letters, 1, 1) = substring(letters, 3, 1) ), letters; That is, compare the initial character to the next two. The above returns 0, when the first and second characters are different; 1, when the first and second are the same but the third different; and 2 for three character prefixes.

Categories : Mysql

whats wrong with my capitalize letters in words code?
When your function is called, the very first thing it's doing is: return str.charAt(0).toUpperCase()+ str.slice(1); This returns the first character of the string converted to upper case, plus the rest of the string (as is) starting from index 1. Since the function returns from there, nothing else in your function is being executed. How about something like: function LetterCapitalize(str) { var words = str.split(' '); // create an array of each word for(var i = 0; i < words.length; i++) // Loop through each word words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1); // capitalize first character of each word return words.join(' '); // join the array back into a string } Also, if you're simply trying to do this for display purposes, you can use the

Categories : Javascript

during cast of a char value in java question mark is printed on console
A char can't be negative, so when you write: char b = (char) -65; you have an overflow and the actual value is 65,536 - 65. You can verify it with System.out.println((int) b); which prints: 65471 That character is probably not handled by your console and could appear as a blank or a square for example.

Categories : Java

What is wrong with my regex in finding unnecessary char before "void main"
It is much easier to search for the conditions you accept, and error on anything else, with this regex: ^s*voids+main$ Use it like this: if( /^s*voids+main$/.test(kword_search) == false ){ alert('found unnecessary char(s) before keyword main'); }

Categories : Javascript

NSDate dateWithTimeIntervalSince1970 displays wrong timestamp to console
The date is correct. When printing to the console the description of the date is used and that uses your system locale so it applies your time zone to the date before printing. When you want to display the time you need to use a date formatter to convert the date into a string. The important part is setting the locale / time zone that the formatter uses. Take a read of this and this.

Categories : Objective C

jquery after filtering element "click" event gives wrong no.of console
I've got this working in the following example, take a look and see if it solves your problem. Example HTML: <form> <input type="checkbox" name="checkbox1" value="Aus" /> <input type="checkbox" name="checkbox2" value="US" /> </form> Example JS: var serverValue = { name: "US" }; var userLocales = $('input[type="checkbox"]', "form") .filter(function() { return $(this).val() === serverValue["name"]; }) .prop("checked", true) .addClass("userLocales").on("change", function() { console.log($(this).prop("class")); }); var plainLocales = $('input[type="checkbox"]', "form") .filter(function() { return $(this).hasClass("userLocales") !== true; }) .on("change", function() { console.log("i am fresh

Categories : Jquery

Hash function which returns not just lowercase letters and numbers, but also symbols and uppercase letters
You seem to refer to the hexdecimal-ascii representation ("letters and numbers") of the hash. That's just a different way of saying "number", only with sixteen symbols instead of ten as in decimal or two in case of binary. You can map the hash - which is just a number like any other - to any representation you want. You may, for example, base85-encode the hash which gives you a ascii-string like ">uD.RTpAKYo'+CT/5+Cei#DII?(E,9)oF*2M7/c~>", depending on the size of the hash.

Categories : PHP

Algorithm and Data Structure for Checking letters in a word with another set of letters
This is for something like Scrabble or Boggle, right? Well, what you do is pre-generate your dictionary by sorting the letters in each word. So, word becomes dorw. Then you shove all these into a Trie data structure. So, in your Trie, the sequence dorw would point to the value word. [Note that because we sorted the words, they lose their uniqueness, so one sorted word can point to multiple different words. ie your Trie needs to store a list or array at its data nodes] You can save this structure out if you need to load it quickly later without all the sorting steps. What you then do is take your input letters and you sort them too. You then start walking through your Trie recursively. If the current letter matches an existing path in the Trie, you follow it. Because you can have

Categories : Java

ObjC / iOS - Capitalize first letters of each word without modifying other letters
Try this - (NSString *)capitilizeEachWord:(NSString *)sentence { NSArray *words = [sentence componentsSeparatedByString:@" "]; NSMutableArray *newWords = [NSMutableArray array]; for (NSString *word in words) { if (word.length > 0) { NSString *capitilizedWord = [[[word substringToIndex:1] uppercaseString] stringByAppendingString:[word substringFromIndex:1]]; [newWords addObject:capitilizedWord]; } } return [newWords componentsJoinedByString:@" "]; }

Categories : IOS

How to convert roman-latin letters into Japanese letters?
public class Converter { public String RomajiToHiragana(String wordRomaji) { wordRomaji = wordRomaji.toLowerCase(); // Seion if (wordRomaji.contains("kya")) { wordRomaji = wordRomaji.replace("kya", "きゃ"); } if (wordRomaji.contains("kyu")) { wordRomaji = wordRomaji.replace("kyu", "きゅ"); } if (wordRomaji.contains("kyo")) { wordRomaji = wordRomaji.replace("kyo", "きょ"); } if (wordRomaji.contains("sha")) { wordRomaji = wordRomaji.replace("sha", "しゃ"); } if (wordRomaji.contains("shu")) { wordRomaji = wordRomaji.replace("shu", "しゅ"); } if (wordRomaji.contains("sho")) { wordRomaji = wordRomaji.replace("sho", "しょ"); } if (wordRomaji.contains("cha")) { wordRomaj

Categories : Android

Convert special letters to ascii letters in java
Generally speaking, ASCII is very poor and old character table and it actually doesn't contain wanted characters. But what about your issue, it isn't related to ASCII table. Java works with unicode. Just what you need is include such symbols into your regexp, something like [^a-zA-Z0-9äàèçîñö]. The core problem is that such regular constructions as a-z or A-Z (called symbol classes) don't include such special national symbols. You have to include them manually.

Categories : Java

is char** x = (char**) arg equivalent to reinterpret_cast(const_cast(arg) )?
Yes they are basically the same except the c++ style cast shows the reader of the code that you are doing some weird stuff while its harder to notice with the c style. Its legal yet as always its highly suspect when a const incoming parameter is being cast as non const.

Categories : C++

Removing letters from a list of both numbers and letters
You can use str.translate to filter out letters: >>> from string import letters >>> strs = "6483A2" >>> strs.translate(None, letters) '64832' There's no need to convert a string to a list, you can iterate over the string itself. Using str.join, str.isdigit and list comprehension: >>> ''.join([c for c in strs if c.isdigit()]) '64832' or this as you want the sum of digits: sum(int(c) for c in strs if c.isdigit()) Timing comparisons: Tiny string: >>> strs = "6483A2" >>> %timeit sum(int(c) for c in strs.translate(None, letters)) 100000 loops, best of 3: 9.19 us per loop >>> %timeit sum(int(c) for c in strs if c.isdigit()) 100000 loops, best of 3: 10.1 us per loop Large string: >>> strs = "6483A2"*1000 >&g

Categories : Python

C++ I cannot cout one string while i successfully cout an another string
The size of dec is zero. But you access elements at positions 0 to 3. You could for example create dec initialized to the appropriate size by using string dec(4, ' '); // fill constructor, creates a string consisting of 4 spaces instead of string dec; .

Categories : C++

Screen readers: How to make a word with tags surrounding its letters be spoken as a single word, rather than a series of letters?
This not a solution but it might be an useful workaround if your situation allow you. I felt you want to wrap one letter to render that differently, instead you can show the word "test" as an image by doing so you can create it any way you want and put the word "test" as alt attribute in image <h1>This is a <span id="specialWord" ><img src = "testImage.jpg" alt = "test"></span>. </h1> So if it is like that OS X voice over will read it properly. Because if I remember correctly it reads the alt attribute of an image. Now in that case a problem might arise. Anybody want to select it as a text then it would not be possible. You can solve that by calling a javascript function to dynamically change the inner html of the span tag (with id="specialWord" ) to "

Categories : HTML

typecasting vs memcpy() : which one is better?
Your typecasting, besides that you got the syntax a bit wrong, has undefined behavior, because your struct may of different size, due to padding and have specific alignement properties. Don't do it like this.

Categories : C++

strncpy() and memcpy() are different?
strncpy((char *)array2, (char*)array1 , sizeof(array1)); Casting array1 to a char * doesn't do what you want. There are no characters at that location, there are only integers (little-endian it seems). What is happening is that strncpy copies bytes from the integer array until it reaches a 0 byte, which is pretty soon. On the other hand memcpy doesn't care about 0 bytes and just copies the whole thing. To put it another way, strncpy finds a 0 byte "inside" the first integer and stops copying; it does however fill the destination buffer with zeros up to the specified size.

Categories : C

how the following memcpy is beyond array in C?
In Master, you have only Student students[TIME_STUDENTS][NUM_STUDENTS]; and TIME_STUDENTS is smaller than NUM_STUDENTS, so memcpy(&info.student[0][0], &master.student[0][0], sizeof(Student) * NUM_STUDENTS * NUM_STUDENTS); copies more bytes than the source has.

Categories : C

How to use memcpy in Struct in c?
You have to be careful to only copy the size of the smaller of the two, here I suppose that i < MAX_POINTS memcpy(pt, temp, sizeof pt); Also as others already said the & are not correct. You need a pointer to the first element, that is &pt[0] for example, or just pt as the array decays to &pt[0] in that context. Note that your allocation of pt is a variable length array if i is a variable. This can be dangerous and lead to a stack overflow if i is getting too large. So if you plan to use large arrays here, better use malloc: struct points* pt = malloc(sizeof(struct points[i])); memcpy(pt, temp, sizeof(struct points[i]); Unfortunately then, you can't use sizeof pt for the memcpy.

Categories : C

Using 'memcpy' function
1) In C, all arrays are really just bytes of data in a long sequence, one after another. There is no interspersed meta data or anything like that, so copying the bytes of an array, means copying the array itself with no loss of data, regardless of what type the array is made up of. Only the total size matters. 2) This is as Kerrek SB said, "because you cannot have function arguments of array type in C". That ties in with 1 - since there is no meta data in C arrays, the function gets no information on how large an array is, just where in memory it begins. The size is so it can know when to stop write data.

Categories : C

Templatized ostream overload ambiguity error : basic_ostream vs const char[]
The non-template operator does not cause any ambiguity because that operator itself is not viable for resolving this call: return out << "a1"; // ^^^^^^^^^^^ // This MUST be `std::operator <<`, no other valid overload of // operator << is found! As well as the other similar ones. The template version, on the other hand, is viable, since T is not bound to be any concrete type: template <class T> ostream& operator<<(ostream& out, const T& a) { switch(a) { case T::a1 : return out << "a1"; // ^^^^^^^^^^^ // Here the compiler could invoke std::operator << // OR it could invoke your operator << template, // which is also viable since T could be anything! //

Categories : C++

Unable to pass an address of array of type char *[2] to function taking char ***
char *array[2] = {"string", "value"}; is an array with 2 elements of char *. Using array as an address results to a pointer to the first element, i. e. of type char **. Using &array results to a pointer to the same place, but of type char *(*)[2] (not sure if the spelling is right). This is not the same as a char *** - the representation in memory is completely different. To be more verbose, +++++++++++++++++++++++ + array[0] + array[1] + +++++++++++++++++++++++ this is the array. char ** p1 = array; // is a pointer to the first element, which in turn is a pointer. char *(*p2)[2] = &array; // is a pointer to the whole array. Same address, but different type, i. e. sizeof(*p1) != sizeof(*p2) and other differences. char ***p3 = &p1; // Now, p1 is a different pointer va

Categories : C

char pointers, char arrays, and strings in the context of a function call
The char[] signature in the parameter is exactly the same as char*. In C++, it is illegal to convert a string constant char const* (the string "Kacy") to a char* because strings are immutable. Your second example compiles because the name is an actual array. There is no change to char*. As a solution, change your parameter to take a const string array: Student(char const name[]); which again is the same as String(char const *name); though you're better off using std::string: #include <string> class String { public: String(std::string name); };

Categories : C++

How to disable type char in JTextArea but enable removed char (Backspace)
try to put DocumentFilter instead of DocumentListener something like final AbstractDocument abstractDocument = (AbstractDocument) textArea.getDocument(); abstractDocument.setDocumentFilter(new DocumentFilter() { @Override public void remove(final FilterBypass fb, final int offset, final int length) throws BadLocationException { super.remove(fb, offset, length); } @Override public void insertString(final FilterBypass fb, final int offset, final String string, final AttributeSet attr) throws BadLocationException { if (getLineCountAsSeen(textArea) < 4) { super.insertString(fb, offset, string, attr); }

Categories : Java

C - Sort char string in array to equal char user input
OK, so basically you want to convert a sorted array of letters to a specific (random?) ordering and record the swaps along the way, right? Here is one way to do this. #define SWAP(a,b) a^=b;b^=a;a^=b int main(int argc, char* argv[]) { char* wordInput=argv[1]; char* newWord = (char*)malloc((strlen(wordInput) + 1) * (sizeof(char))); int i,j,k; fprintf(stdout, "Word is %s ", wordInput); // Sort wordInput into newWord. for (i=0; i<strlen(wordInput); i++) { // Put this one at the end. newWord[i]=wordInput[i]; // Start at the back of the string, and move it forward if it is less. for (j=i-1; j>=0; j--) { if (newWord[j+1] < newWord[j]) { SWAP(newWord[j+1], newWord[j]); } else { break; } } } newWord[strlen(wordInput)]

Categories : C

how to memcpy the two dimensional array in C?
I don't think it's correct, no. There's no way for memcpy() to know about the in-memory layout of a and "respect" it, it will overwrite sizeof c adjacent bytes which might not be what you mean. If you want to copy into a "sub-square" of a, then you must do so manually.

Categories : C

how memcpy is handled by DMA in linux
There are architectures where the bus between the CPU and memory is rather weak; some of those architectures add a DMA engine to allow big blocks of memory to be copied without having a loop running on the CPU. In Linux, you would be able to access the DMA engine with the dmaengine subsystem, but it is very hardware-dependent whether such an engine is actually available. X86 CPUs have a good memory subsystem, and also have special hardware support for copying large blocks, so using a DMA engine would be very unlikely to actually help. (Intel added a DMA engine called I/OAT to some server boards, but the overall results were not much better than plain CPU copies.) DMA forces the data out of the CPU caches, so doing DMA copies for your program's variables would be utterly pointless becaus

Categories : C

Memcpy with a void pointer
data needs to point to somewhere you have access to write. The null pointer area you don't have access to (unless you're running DOS or something). Use malloc to allocate a chunk of memory to copy from inputData to.

Categories : C

C++ memcpy to a malloc'ed memory
CString is not a POD type and cannot be bitwise copied. It seems you have to switch paradigms from C to C++ From the docs it seems like http://msdn.microsoft.com/en-us/library/aa300569(v=vs.60).aspx supports a conversion: LPCTSTR raw = (LPCTSTR) Message; // now memcpy from `raw`

Categories : C++

Refactoring use of stringstreams with memcpy
Both std::stringstream and memcpy are inefficient for this type of operation. Just access the buffer directly like so... bool Record::was_marked_as_deleted() { if (buffer == NULL || size_of_buffer < 3) return false; unsigned short size_of_first_field = reinterpret_cast<unsigned short*>(buffer)[0]; if (size_of_first_field > 1) return false; if (buffer[3] != MARK_DELETED) return false; return true; } Or use a data structure... bool Record::was_marked_as_deleted() { if (buffer == NULL || size_of_buffer < 3) return false; // Add packing directives if necessary. i.e. #pragma pack struct Data { unsigned short size; char flag; }; Data *field = reinterpret_cast<Data*>(buffer); if (field-

Categories : C++

memcpy qt and compile error
memcpy(&(args[1],&report,sizeof(ABC::report))); Should be memcpy(&(args[1]),&report,sizeof(ABC::report)); You should also ensure that args is sufficiently large to hold the result.

Categories : C++

is it possible to do memcpy in bits instead of bytes?
If you need to fill fields, you can use C bit-fields with a struct, like this: struct box_props { unsigned first : 1; unsigned second : 3; unsigned : 4; }; Where 1, for instance, means that the field is 1bit long. The last (unnamed) field means: 4bit padding. Define struct, memcpy to it and read fields as if they where unsigned. Same for writing. NOTE: always pad to integer byte, or memcpy could have unwanted effects.

Categories : C



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.