Reputation: 367
While working on a basic coding challenge I have come across a confusing situation that i am unable to fathom the cause of (I am new to programming)
whilst attempting to split a number into its individual digits, my int array contains the value 13 but returns the value 49??
there is probably an obvious reason for this and if so i apologize.
I have found an alternate way to split my numerical string into individual digits but would still like to know what i was doing wrong
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AddTheDigits
{
class Program
{
static void Main(string[] args)
{
using (StreamReader reader = new StreamReader("TextFile1.txt"))
{
//int total = 0;
string line = reader.ReadLine();
//Console.WriteLine(line); //testing
char[] charArray = line.ToCharArray(0,1);
int[] intArray = new int[charArray.Length];
for (int i = 0; i < intArray.Length; i++)
{
intArray[i] = Convert.ToInt32(charArray[i]);
Console.Write(intArray[i]);
}
}
Console.ReadLine();
}
}
}
Upvotes: 1
Views: 83
Reputation: 46323
you're taking you line
(Which probably contains '13'), and grabbing the first char
in it (line.ToCharArray(0,1);
). You then convert this char (which has the numerical value 49, equal to '1' in UTF-16) to an int (still equals 49) and you print it. That's it. the '3' is left out due to the ToCharArray
only grabbing the first character.
Upvotes: 2
Reputation: 8814
49 is ASCII code for 1.
Instead of using Int32.Convert
, you should use Int32.Parse
.
Upvotes: 0
Reputation: 25370
What you are doing is essentially:
"13".ToCharArray(0,1);
which will give you the same value as :
char c = '1';
which is 49, the ASCII code for '1'
Upvotes: 0
Reputation: 32497
You are probably mixing up the ASCII code for the digits with the digits themselves. Try replacing
intArray[i] = Convert.ToInt32(charArray[i]);
with
intArray[i] = charArray[i] - '0';
and see if that helps.
Upvotes: 2