Unreal Engine 4 - Export variable - variables

I'm new to unreal engine 4 and have a relatively simple question. How can i export a value from a variable to a .txt file?
I tried "WriteToFile" but can't get it to work. Any help is appreciated.

I don't know what your variable's type is. Text files are strings, so an FString can be directly saved to a text file. Anything else you will need to convert.
A number can be converted to a string in many ways (a string of the digits, an octet, or something like Base64). For this example I will assume a number would be saved as the text representation of its digits (i.e. an int32 of value 100 number would become an FString with the value "100").
// .cpp
void SomeClass::SomeFunction() {
FString YourString;
// if saving a string, just make a string
YourString = TEXT("This is some text");
// if saving an integer, convert it to string
int32 YourInteger = 100;
ourString = FString::FromInt( YourInteger );
// or if it's a float, convert it as well
float YourFloat = 3.14f;
YourString = FString::SanitizeFloat( YourFloat );
// then, save it to file
FString Filename = TEXT("some kind of file path here");
FFileHelper::SaveStringToFile(YourString, *Filename);
}

Related

How to Avoid User String Inputs in Objective-C

My program asks for an integer input and I want to make sure (error trap) that the program would print "invalid" if the user inputs a string or any other character.
I'm new to Objective-C, hope you'll understand.
NSLog(#"1. Apple 2. Orange 3. Mango 4. Banana");
NSLog(#"Choose fruit:");
scanf("%d", &fruit);
**if(fruit>4 || fruit<1){
//If the user inputs any number other than the choices.
NSLog(#"Invalid.");
}
else if(...){
//if the user inputs a string or character
}**
I expecting the program would print "Invalid" if it would input a character or string or anything besides the choices.
Im not sure if you still require an answer . Im also fairly new so anyone feel free to add . Im not sure if this is meets your exact requirements but it does what you want it to . Instead of tryign to check for each and every data type what i suggest is check if the entered value is an integer or not . If it is do something else return the error message .Take a look at the below code .
int main(int argc, const char * argv[]) {
char str[50] = {0}; // init all to 0
NSLog(#"1. Apple 2. Orange 3. Mango 4. Banana");
NSLog(#"Choose fruit:"); // print buffer
scanf("%s",str);
// you can create an NS foundation NSString object from the str buffer
NSString *valueEntered = [NSString stringWithUTF8String:str];
if([valueEntered integerValue]){
printf("do somethinng here\n");
}
else{
printf("Not an integer\n");
}
}
First take the user's input as a NSString , so we can transfer it to a Integer value later onwards. The reason i have initialised it as a character is because Scanf wont allow to pass a String from what i read . So get the user's input as a character set change it to a String and check if it includes a Integer or not . IntegerValue returns the integer that the string holds if there is one , else it returns 0 .
Another method you can try is using ScanInt method in NSScanner. Issue with that is it will check if it includes a integer and return true . So something like "abc32" will also be true in that manner so probably wont be usefull for you .
Please let me know if this is what you expect as i also learnt a few things trying to solve this :)
Check the return value of scanf.
Having said that, using scanf for interactive input is often a recipe for confusion, so it might be a better idea to read input into a string with something like fgets and then analyze the string (possibly, but not necessarily, with sscanf).

NumberFormatException in converting string to byte

I am trying to get the MD5 format of string
Code:
fun getEncodedData(data: String): String? {
val MD5 = "MD5"
// Create MD5 Hash
val digest = java.security.MessageDigest
.getInstance(MD5)
digest.update(data.toByte())
val messageDigest = digest.digest()
// Create Hex String
val hexString = StringBuilder()
for (aMessageDigest in messageDigest) {
var h = Integer.toHexString(0xFF and aMessageDigest.toInt())
while (h.length < 2)
h = "0$h"
hexString.append(h)
}
return hexString.toString()
}
There is a crash at: digest.update(data.toByte()). I get number format Exception
Input I am passing for data: oEXm43
There is no crash if I pass ex: 11 as a string for input data
Should the input always should be integer in the string or can it be a mixture of number and characters.
You're trying to call the update method that takes a single byte parameter, and using toByte which converts the entire string's numerical value to a single byte. This conversion method is what fails on non-numerical values inside a String.
Instead, you can use the variant of update with a byte[] parameter, and convert your String to an array of bytes (one per character) with toByteArray:
digest.update(data.toByteArray())

Convert a string into a int

I need some help here, I am currently making a game, but I got stuck somewhere. So, what I want is, if a Labels text is higher then the other labels text, then something will happen, I typed If Label26.Text > Label24.Text Then Label33.Visible = True which seems not to work, please, I need some help here, thanks. And yes, the labels text is NUMBERS.
The Text property of a label is a string. As far as computers go, you can't do math (using comparison operators like > will not return the result you are expecting) with strings because they are just a sequence of characters.
Even if the string only contains a number, the computer still sees it as a sequence of characters and not a number ("5" is a string literal with the character 5 in it, while 5 is an integer that can be used in a mathematic expression).
As some of the other commenters mentioned, you need to cast the Text property to an Integer or Double (or some other numeric data type). To do so, you'd want to use Int32.Parse to change the strings to integers.
If Int32.Parse(Label26.Text) > Int32.Parse(Label24.Text) Then Label33.Visible = True
You can use the int.tryParse to check if the content of the variable is a number or not. The output of the TryParse is a boolean, see the example below:
int num1 = 0;
bool num1_ = false;
num1_ = int.TryParse(txt1.Text.ToString(), out num1);
if (num1_)
{
// Is a number/integer
//Do something
}
else
{
//Is a string
//Do something else
}

java.text.DecimalFormat equivalent in Objective C

In java, I have
String snumber = null;
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number); //'number' is of type 'long' passed to a function
//which has this code in it
I am not aware of the DecimalFormat operations in java and so finding it hard to write an equivalent Obj C code.
How can I achieve this? Any help would be appreciated.
For that particular case you can use some C-style magic inside Objective-C:
long number = 123;
int desiredLength = 10;
NSString *format = [NSString stringWithFormat:#"%%0%dd", desiredLength];
NSString *snumber = [NSString stringWithFormat:format, number];
Result is 0000000123.
Format here will be %010d.
10d means that you'll have 10 spots for number aligned to right.0 at the beginning causes that all "empty" spots will be filled with 0.
If number is shorter than desiredLength, it is formatted just as it is (without leading zeros).
Of course, above code is valid only when you want to have numbers with specified length with gaps filled by zeros.
For other scenarios you could e.g. write own custom class which would use appropriate printf/NSLog formats to produce strings formatted as you wish.
In Objective-C, instead of using DecimalFormat "masks", you have to live with string formats.

Some info about CC_SHA256 objective-c

For a new project I need to hash a NSString with SHA256.
I have used the following code:
unsigned char hashedChars[32];
NSString *inputString;
inputString = [NSString stringWithFormat:#"hello"];
NSData * inputData = [inputString dataUsingEncoding:NSUTF8StringEncoding];
CC_SHA256(inputData.bytes, inputData.length, hashedChars);
I found this piece of code on stackoverflow.
I do not really get all the things this code do here are some questions about the code:
1.The CC_SHA256 makes a hash but this hash will be stored in inputData again? What I mean can I do something like this:
NSString *string=CC_SHA256(..) //of course you can't put it directly in a NSString, but you get the point
2.In the end the hash has to be a hexadecimal string, but what is the type that CC_SHA256 outputs (UTF-8??)?
3.The first parameter of CC_SHA256 why do I have to put bytes at the end and is "inputData" enough?
4.What is the need of the length of the string (second parameter)?
5.And the last parameter does not make any sense to me, can somebody please explain and why the hashedChars has to be 32?
The argument list for CC_SHA256 is:
extern unsigned char *CC_SHA256(const void *data, CC_LONG len, unsigned char *md);
From the man page: https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/CC_SHA256.3cc.html
Parameters explained:
*data is the input string, what you want to be hashed. It's a C string-type. A way to get this is to call 'inputData.bytes', with inputData a NSData object.
len is the length of the input string. As you'll realize if you'll start working with C strings, it's pretty normal for functions working with strings to ask for the length. That's because in C strings are just a sequence of bytes, and while text strings are generally terminated by a null byte, binary strings can have any length. It's also for safety ("buffer overflows").
*md is the output. Again, this is returned as a C string, of fixed length 32 bytes for SHA256 (that's why you don't see an outputLength parameter).
The output is "not relevant", but can be used to check if the function ran properly: if(CC_SHA256(...)) { all ok; }
The result string is stored into *md, and it's a binary C string, 32 bytes long. It's 32 bytes long because that's the length of SHA256 digests; for example, 16 bytes for MD5, 20 bytes for SHA1, etc. It's just how the algorithm works!
The output is just a binary string. If you want to make it into hex format you need to store it into a NSData object, and then get a hex representation of it:
NSData *resultData = [NSData dataWithBytes:hashedChars length:32];
To get the hex representation then look at this SO answer: https://stackoverflow.com/a/25378464/192024
If anyone trying to find a similar function for Android, the below snippet produces the same output as CC_SHA256
public static String calculateSH256(String secret){
final MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-256");
byte[] bytes = secret.getBytes("UTF-8");
digest.update(bytes, 0, bytes.length);
String sig = bytesToHex(digest.digest());
return sig;
}
catch (NoSuchAlgorithmException | UnsupportedEncodingException e){
throw new RuntimeException("Cannot calculate signature");
}
}
final protected static char[] hexArray = "0123456789abcdef".toCharArray();
private static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}