I'm having trouble converting a string to a integer, my program is failing on this line
int newS = int.Parse(s);
With message:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
The number I'm expecting back from my program is rather large. Below is the total program:
int math = (int)Math.Pow(2,1000);
string mathString = math.ToString();
List<string> list = new List<string>();
char[] ch = mathString.ToCharArray();
int result = 0;
foreach (char c in mathString)
{
string newC = c.ToString();
list.Add(newC);
//Console.WriteLine(newC);
}
foreach (string s in list)
{
int newS = int.Parse(s);
result += newS;
}
Console.Write(result);
Console.ReadLine();
You answered your own question. An int can only store numbers up to 2147483648 and an unsigned int up to 4294967296. try to use an ulong instead. I'm not sure about this but maybe a signed long may work.
EDIT: actually, in the msdn page it says this:
If the value represented by an integer literal exceeds the range of ulong, a compilation error will occur.
So probably you need a double.
Math.Pow(2, 1000) returns -2147483648.
So you'll end up with 11 items in your list, the first one being "-".
You can't convert a minus sign to int.
In all of the types of all languages are a limit on the numbers that you can save.
The int of c# is -2,147,483,648 to 2,147,483,647.
https://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx
Math.Pow
returns a double, when you want to cast it to int your variable gets the value 0
Math.Pow(2,1000) returns: 1.07150860718627E+301.
If you use the double format you will try to cast the . and the E and the +, that are not a int then you can't use a int to save it.
that returns the FormatException that are answered here:
int.Parse, Input string was not in a correct format
Maybe you can try this:
int newS;
if (!int.TryParse(Textbox1.Text, out newS)) newS= 0;
result +=newS;
But will not use the 301 digits of the solution of 2^1000.
Related
I want to know why following shows an InvalidCastException:
Object obj = 9;
long num = (long)obj; //InvalidCastException
After searching on net I find out Object considers 9 as Int so long doesn't exactly match Int.
My question is why Object considers 9 as Int but not short or long?
Because 9 is an Int32 literal. To specify an Int64 literal use
Object obj = 9L;
long num = (long)obj;
You can actually make this work if you explicitly say that it's a long. Pure numbers are read as integers, unless there are decimal points.
Object obj = 9L;
long num = (long)obj;
The following will also result in an invalid cast exception:
Object obj = 9L;
int num = (int)obj; //InvalidCastException
int is the default data type for non-decimal numeric literals, just as double is the default for decimal numeric literals. You can force numeric literals to other types with appropriate suffixes. You can use suffixes for int and double too but pretty much noone ever does.
1)
class Program
{
static void Main(string[] args)
{
int a;
a = Convert.ToInt32( "a" );
Console.Write(a);
}
}
I get FormatException with message: Input string was not in a correct format. and this is quite understood.
2)
class Program
{
static void Main(string[] args)
{
int a;
a = Convert.ToInt32( Console.Read() );
Console.Write(a);
}
}
In second case, I can type any characters, for example abc and it displayed in console.
Question: Why doesn't throw FormatException in second case and why it works successfully with non int characters?
UPDATE
with Console.ReadLine() method, which returns string type, also not trown FormatException and printed any character in console successfully.
class Program
{
static void Main(string[] args)
{
int a;
a = Convert.ToInt32(Console.ReadLine());
Console.Write(a);
}
}
The return type of Console.Read() is an int.
You then call Convert.ToInt32(int):
Returns the specified 32-bit signed integer; no actual conversion is performed.
Because the output of the Console.Read() is int. It means it get the int representation of what you have typed, so if you type character it actually get the int representation of that character, and everything is ok.
To see what is happening in detail:
int a;
a = Convert.ToInt32(Console.Read()); //input for example: abc
Console.WriteLine(a); //97
Console.WriteLine((char)a); //a
Return Value Type: System.Int32 The next character from the input
stream, or negative one (-1) if there are currently no more characters
to be read.
public static int Read()
Reference
FormatException : Value does not consist of an optional sign followed by a sequence of digits (0 through 9).
I strongly suspect you are mixing with Console.ReadLine and Console.Read methods.
From Console.Read doc;
Reads the next character from the standard input stream.
and
Return Value Type: System.Int32 The next character from the input
stream, or negative one (-1) if there are currently no more characters
to be read.
That means when you put abc with this method it returns 97 (because 97 is the ascii value of the first character) which is a valid integer.
https://msdn.microsoft.com/en-us/library/sf1aw27b(v=vs.110).aspx
ToInt32 does have an overloaded version that can take a string, but the string must be a representation of a real number; "a" is not a number, but if you had "101" it would parse correctly-
int a;
a = Convert.ToInt32("101"); //will parse to int
Console.Write(a);
a = Convert.ToInt32("a"); //will not parse to int
Console.Write(a);
The reason your second example works while the first one doesn't, is because Console.Read returns the integer value based on the next character passed into it, so all is fine when you call ToInt32 with it.
UPDATE-
Just tested it with ReadLine too, and it still gave me an error.
Is there any class in C# similar to Numberformat class in Java which, verify the string is a number.
NumberFormat numberFormat = NumberFormat.getInstance();
Number number = numberFormat.parse(string);
while trying for float with following parameter
float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out fValue),
the value=6666.77777 is rounded of to 6666.778.
can anyone help, i don't want my value to be rounded.
use int.TryParse it will return true if the number is int.
int.TryParse for integers.
float.TryParse for floats.
double.TryParse for doubles
Int64.TryParse for long.
e.g.
string str = "123";
int temp;
if (int.TryParse(str, out temp))
{
//its an int
}
else
{
// not an int
}
int a
bool isNumber = int.TryParse("500", out a);
replace int with whatever number you want to check for
I have the following code:
int a = 50;
float b = 50.60f;
a = int.Parse(b.ToString());
On run time this parsing gives as error. Why it is please guide me.
Thanks
It's trying to parse the string "50.6" - that can't be parsed as an integer, because 50.6 isn't an integer. From the documentation:
The s parameter contains a number of the form:
[ws][sign]digits[ws]
Perhaps you want to parse it back as a float and then cast to an integer?
a = (int) float.Parse(b.ToString());
This is because int.Parse throws NumberFormatException if the string does not contain a parsable integer; 50.6 is not a prasable integer.
You are trying to parse a string that does not represent an integer into an integer.
This is why you are getting an exception.
It gives an error because you are trying to parse as int a string representing a float.
float b = 50.60f; // b = 50.6
// b.ToString() = "50.6" or "50,6" depending on locale
// int.Parse("50.6") MUST give an error because "50.6" is
// not a string representation of an integer
What is it that you want to do? Convert a float to an int? Just do this:
float b = 50.6f;
int a = (int)b;
That will truncate the value of b to simply 50.
Or do you want it rounded off to the nearest integer?
int a = (int)Math.Round(b);
Is the error message not specific enough?
Input string was not in a correct format.
int.Parse must take a string which can be parsed to an integer. The string "50.6" does not fulfil that requirement!
So TextReader.ReadLine() returns a string, but TextReader.Read() returns an int value. This int value also seems to be in some sort of format that I don't recognize. Is it possible to convert this integer to a character? Thanks for any help.
EDIT:
TextReader Values = new StreamReader(#"txt");
string SValue1;
int Value1;
Value1 = Values.Read();
Console.WriteLine(Value1);
Console.ReadKey();
When it reads out the value it gives me 51 as the output. The first character in the txt file is 3. Why does it do that?
According to the documentation for the StringReader class (a sub-class of TextReader), the return value of Read() can be converted to a char, but you need to check if you're at the end of file/string first (by checking for -1). For example, in this modified code from the documentation:
while (true)
{
int integer = stringReader.Read();
// Check for the end of the string before converting to a character.
if (integer == -1)
break;
char character = (char) integer; // CONVERT TO CHAR HERE
// do stuff with character...
}
The documentation tells you: it returns -1 if there is no more data to read, and otherwise it returns the character, as an integer. The integer is not "in some sort of format"; integers are raw data. It is, rather, characters that are "formatted"; bytes on the disk must be interpreted as characters.
After checking for -1 (which is not a valid character value and represents the end of stream - that's why the method works this way: so you can check), you can convert by simply casting.
Read returns an int o that end-of-stream (-1) can be detected. Yes, you just cast the result to a char as in var c = (int) reader.Read();.
Typical usage:
while (true)
{
int x = reader.Read();
if (x == -1) break;
char c = (char) x;
// Handle the character
}