Ok, hey. I made a program for an in-game.. game. And I have it load data for a player from their own .txt on my computer. Whenever i try to command (.load) it tells me (at split[1] where it is converted to an int32) which is just a test to see if your bombs load, input string is not in correct format, heres the code:
StreamReader streemy = new StreamReader(#"c:\Usernames\" + player[m.GetInt(0)].username + ".txt");
string read = streemy.ReadToEnd();
if (!string.IsNullOrEmpty(read))
{
string[] split = read.Split('=');
player[m.GetInt(0)].bombs = Convert.ToInt32(split[1]);
Say(names[m.GetInt(0)].ToUpper() + ": You data has been loaded!");
streemy.Close();
}
else
{
Say(names[m.GetInt(0)].ToUpper() + ": Your data was empty :( Say '.save' to save your current data!");
}
.save Saves the data to the .txt, "names[m.GetInt(0)]" is their username, Say just tells them in the game the message. Thanks for your help! PS: player is a struct, which has ints like bombs.
I would suggest you to use Int32.TryParse instead of Convert.ToInt32.
So if the value is not valid integer then you can treat as 0 or no bomb.
int numberOfBombs = 0;
bool result = Int32.TryParse(value, out numberOfBombs);
now numberOfBombs would retain the actual value if there is valid integer field present otherwise it will be 0.
You must be getting a FormatException.
FormatException is thrown when the arguement is not in valid format.
I think that the value of split[1] is not a valid integer.
According to msdn.
FormatException : value does not consist of an optional sign followed by a sequence of digits (0 through 9).
Using the ToInt32(string) method is equivalent to passing value to the Int32.Parse(String) method. value is interpreted by using the formatting conventions of the current thread culture.
You can call the Int32.TryParse method instead. It returns a Boolean value that indicates whether the conversion succeeded or failed.
Related
I'm trying to convert a string array (which I populated from a .txt file) to a double array in C#.
This is what I've tried, using a for loop, which I've seen on other solutions.
string[] StringArr = File.ReadAllLines("256.txt");
double[] DoubleArr = new double[StringArr.Length];
for(int i = 0; i < StringArr.Length; i++)
{
DoubleArr[i] = Convert.ToDouble(StringArr[i]);
}
This threw the exception "System.FormatException: 'Input string was not in a correct format." for
DoubleArr[i] = Convert.ToDouble(StringArr[i]);
I thought there was something wrong with the format of the data from the text file, but when I tried
DoubleArr[0] = Convert.ToDouble(StringArr[0]);
Console.WriteLine(DoubleArr[0]);
this worked without throwing an exception, and printed the correct number.
I assume that I must have done something wrong with the for loop?
without seing your data, you could have a problem of Incorrect decimal separator
Different cultures use different decimal separators ( , and . for example)
If you replace . with , all will be okay
or you use the Culture :
double.Parse("12.345", System.Globalization.CultureInfo.InvariantCulture)
also, you could have an empty value which is an incorrect double
Problem I currently have:
My server returns data back to the client, this includes a name. Now I want the client to grab this name and compare it. However for the past 3 hours I am stuck at this problem and I dont want to cheap fix around it.
My server returns a value and then a name, ex: random23454#NAMEHERE
I split the value using:
string[] values = returndata.Split('#');
And then I am doing:
if (textBox3.Text == values[1]) {
MessageBox.Show("equal");
}
However, the problem here is. I cant get it to be equal, I tried other methods but it just dont display equal.
What I have done:
Print textBox3.Text to a textbox and print values[1] to a other textbox and compared with my eye and mouse (Using invoke due to threading).
Used the .Trim() function
Using the .ToString() on values[1] (Just for the hell of it)
Assigned them both to a complete new string, trimmed them and compared them
Dragged the comparing outside the thread using:
this.Invoke((MethodInvoker)delegate()
{
outside(name);
});
and perform the same check.
My code:
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
if (readData.Contains("#") && readData.Contains("random"))
{
string[] values = returndata.Split('#');
string name = values[1].Trim();
if (textBox3.Text == name)
{
MessageBox.Show("true");
}
else
{
MessageBox.Show("false");
this.Invoke((MethodInvoker)delegate()
{
outside(name);
});
}
What else can I do? I just dont understand that it is not equal..
Thanks in advance.
The data you're getting back from the server could be an array of bytes. Try converting the response to a string first before splitting. Also try printing the response (or the response's type) to console to see what you get before going any further.
Also make sure the length of each string is the same. Maybe give utf-8 a try instead of ASCII? Like so:
System.Text.Encoding.UTF8.GetString(inStream);
string name = values[1].Trim();
I think you want values[2] here. The way I read the documentation for Split, the element at index 1 will be the (blank) separator indicator.
I am trying to convert an object (coming from a SQL server), into a integer so I can format the number to have the correct amount of zero's in front of it.
For example:
If I were to have 25.6, I would need it to be 0025.6.
Now I have looked online on how to do this, but the methods that I have seen people post are not working for me. I am not entirely sure why. I am trying to format GlobalVariables.grossweightafter. I read the value GlobalVariables.grossweight from the SQL server, but then when I TryParse it, it loses its value. The code I have is below:
while (TransferRecord.Read())
{
//Pulling data from the SQL server. getting data for every line of code as specified.
GlobalVariables.baledate = TransferRecord["keyprinter_datetime"];
GlobalVariables.baleline = TransferRecord["pulp_line_id"];
GlobalVariables.baleid = TransferRecord["bale_id"];
GlobalVariables.grossweight = TransferRecord["bale_gross_weight"];
GlobalVariables.grossweightflag = TransferRecord["gross_value_flag"];
GlobalVariables.baleairdrypercent = TransferRecord["bale_airdry_pct"];
GlobalVariables.airdryflag = TransferRecord["airdry_value_flag"];
//Converting the date, and the baleid to fit in the string.
DateTime.TryParse(GlobalVariables.baledate.ToString(), out GlobalVariables.baledateafter);
int.TryParse(GlobalVariables.baleid.ToString(), out GlobalVariables.baleidafter);
int.TryParse(GlobalVariables.grossweight.ToString(), out GlobalVariables.grossweightafter);
GlobalVariables.grossweightafter.ToString("0000.0");
//Calling the WriteData method.
WriteData();
}
So I was wondering if anyone can catch what I am doing wrong, or they can help me out on the correct way to go about this.
What #Hans Passant was saying is that you need to assign the value returned from .ToString. That line should be:
GlobalVariables.grossweightafter = GlobalVariables.grossweightafter.ToString("0000.0");
The last lines should be
if(int.TryParse(GlobalVariables.grossweight.ToString(), out GlobalVariables.grossweightafter))
{
string grossWeightAfter = GlobalVariables.grossweightafter.ToString("0000.0");
//you need to save the string returned from the ToString-method somewhere or it will be lost.
///Alternatively, if GlobalVariables can contain strings aswell:
GlobalVariables.grossweightafter = GlobalVariables.grossweightafter.ToString("0000.0");
}
else
{
//React on value not being an int
}
Maybe you should try to use double.TryParse() method instead of int.TryParse(), because int does not have fractional part?
Also, you need to store ToString() result to a string variable. Your code should be like this:
GlobalVariables.grossweightafterstring = GlobalVariables.grossweightafter.ToString("0000.0");
There is two variable was assigned the value of "003" and "00 3". And it was convert to byte[] as below.
Before:
myStr1 = "003"; // valid, there is no blank inserted.
myStr2 = "00 3"; // invalid, there is one blank character or multi blanks character inserted.
After converted by convert(), if there are blank characters found, the source string will be convert to byte array.
myVal1 = "3"; // valid after convert
myVal2[0] = 0; // invalid, since the source myStr2 is invalid.
myVal2[1] = 1; // same as above.
And now I need determine the source string is valid or invalid based on the converted result. I dont' know how to say the result is an byte array. Could you please give me some advice. Thanks in advance.
input string type source value as SourVal
if (ResultVal is Byte Array) // how to translate the statement to C# code?
SourVal is Invalid;
else if (ResultVal is still String type) // how to translate the statement to C# code?
SourVal is valid;
ps: I failed to try the methods of typeof() and gettype() at my practice. I don't know how to use the methods. Or there is other better method for my validation.
maybe use:
if (ResultVal is byte[]) {
// SourVal is Invalid;
} else if ( ResultVal is String ) {
//SourVal is valid;
}
Try using IsWhiteSpace
//Check the String for Blank spaces if found then don't convert
if(!str.Contains(" "))
{
//use the convert method
}
else
{
//Write Message for an Invalid String
}
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
how can I convert String to Int ?
Hi,
I have the following problem converting string to an integer:
string str = line.Substring(0,1);
//This picks an integer at offset 0 from string 'line'
So now string str contains a single integer in it. I am doing the following:
int i = Convert.ToInt32(str);
i should be printing an integer if I write the following statement right?
Console.WriteLine(i);
It compiles without any error but gives the following error on runtime:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
Any help please?
Rather than using Convert.ToInt32(string) you should consider using Int32.TryParse(string, out int) instead. The TryParse methods are there to help deal with user-provided input in a safer manner. The most likely cause of your error is that the substring you are returning has an invalid string representation of an integer value.
string str = line.Substring(0,1);
int i = -1;
if (Int32.TryParse(str, out i))
{
Console.WriteLine(i);
}
FormatException
value does not consist of an optional
sign followed by a sequence of digits
(0 through 9).
The exception that is thrown when the
format of an argument does not meet
the parameter specifications of the
invoked method.
You can use Int32.TryParse if you don't want to generate an exception like this.
Int32.TryParse: Converts the string representation of
a number to its 32-bit signed integer
equivalent. A return value indicates
whether the operation succeeded.
It's entirely possible there is some whitespace in there. Try running something akin to trim() (I'm not sure what language you're in) that will strip the white space. Also, try printing out the string to make sure you actually have the right part of it. We've all done that :)
It's likely that your input is not a valid format. Try this instead. If the number is not valid, it should output an error.
Keep in mind that the string should consist of an optional sign followed by a number.
string line = "23"; // or whatever.
string str = line.Substring(0,1);
int i = 0;
if (Int32.TryParse(str, out i)) {
Console.WriteLine(i);
} else {
Console.WriteLine ("Error converting '" + line + "', '" + str + "'.");
}
One thing you may be seeing is the user entering "-1" for example. If you do the substring(0,1) on that, you'll only get "-" which isn't really valid.
Are you sure that the value returned in str is an int, set a debug point if your using visual studio. Ive got a feeling your problem maybe that your not actually returning an integer. Try:
line.Trim().Substring(0,1);
This will remove any whitespace.