This question already has answers here:
How could I convert data from string to long in c#
(8 answers)
Closed last year.
The line of code with the issue:
memory.WriteFloat(tp_x, this.X)
this.X is fine and works with no issues.
For the value tp_x, it is a STRING.
I am taking this from a text file and parsing it to an exact value. I have tried several times to convert this string to Int32/64, float, long, etc. But the memory.WriteFloat() is not taking it without an error.
Picture of code
I have tried to use
memory.ReadFloat(tp_X)
But I get the same error.
Cannot convert from 'string' to 'long'. I have tried so much different codes to convert it and use it, but nothing has worked or changed so I am asking a question here. I wouldn't be asking if I had no idea. Thank you, please let me know!
EDITED for pm100
Here is my new code:
Picture 1
Where I get my error Picture 2
So using your code #pm100 as seen in the pictures, I get no problems and I can compile perfectly. Although, when I execute this I get error
I get the error System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Number.ParseInt64(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
at System.Int64.Parse(String s)
My code:
int counter = 0;
// location is the selected index of the combobox that the user selected
foreach (string line in System.IO.File.ReadLines(#"path"))
{
if (counter == location)
{
string[] words = line.Split(",");
int tempcounter = 1;
string tp_x = "";
string tp_y = "";
string tp_z = "";
foreach (var word in words)
{
if (tempcounter == 1)
{
tp_x += word;
}
if (tempcounter == 2)
{
tp_y += word;
}
if (tempcounter == 3)
{
tp_z += word;
}
tempcounter += 1;
//everytime works perfect above, now below
long l = System.Int64.Parse(tp_x);
long l2 = System.Int64.Parse(tp_y);
long l3 = System.Int64.Parse(tp_z);
tp_xx = l;
tp_yy = l2;
tp_zz = l3;
for (int i = 0; i < address.vz.Length; i++)
{
mem.WriteFloat(tp_xx, this.X);
mem.WriteFloat(tp_yy, this.Y);
mem.WriteFloat(tp_zz, this.Z);
}
}
return false;
}
counter += 1;
}
You need Int64.Parse
string s="1234";
long l = System.Int64.Parse(s);
Or if you are not sure that the string contains a valid number use
bool success = Int64.TryParse(s, out long l);
Related
I'm still a noob at working with data so I don't know where to look for more advanced algorithms. Where can I find the info about a string searching algorithm that doesn't require exact input?
I want to make a little programm that works pretty much like this: there are quotes and tags asociated with them, a random tag appears and the user has to input a quote that might be compatible with it, my lil programm searches if it has the quote, returns true or false and shows you the number of mistakes.
Here's what i've done so far
public readonly struct Quote
{
public readonly string[] Tags;
public readonly string TheQuote;
public Quote(string theQuote, params string[] tags)
{
Tags = tags;
TheQuote = theQuote;
}
}
static void MatchTag()
{
Console.WriteLine("Input a quote that might fit the tag");
var input = Console.ReadLine();
var inpL = input.Length;
var allowedMistakes = 5;
var possibleQuotes = quotes.Where(q => q.Tags.Contains(currTag) && inpL.IsInRange(q.TheQuote.Length, q.TheQuote.Length < 10 ? 2 : q.TheQuote.Length / 10));
foreach (var quote in possibleQuotes)
{
var quoteTxt = quote.TheQuote;
int diff = quoteStr.Length - inpL, length, mistakesNum=0;
if (diff < 0)//go through the smallest string to not throw an error
{
length = quoteTxt.Length;
mistakesNum += -diff;
}
else
length = inpL;
bool clear = false;
for (int i = 0; i < length; i++)
{
if (input[i] != quoteTxt[i])
mistakesNum++;
if (mistakesNum > allowedMistakes)
{
clear = true;
break;
}
}
if (clear)
continue;
//show that you are right and return;
Console.WriteLine("The quote fits the tag!");
Console.WriteLine("Mistakes: " + mistakesNum);
return;
}
Console.WriteLine("The quote doesn't fit the tag!");
}
This question already has answers here:
C# parsing a text file and storing the values in an array
(3 answers)
Closed 5 years ago.
I am trying to store values in an array from reading from a file. I have the reading from a file part but I can't get it to store in an array because it gives me an error "Value cannot be null" because after the loop the value of my variable becomes null and the array cannot be null. Here's what I have. And I realize that the for loop probably isn't in the correct spot so any help with where to put it would be great.
Program p = new Program();
int MAX = 50;
int[] grades = new int[MAX];
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
string path = environment + "grades.txt";
StreamReader myFile = new StreamReader(path);
string input;
int count = 0;
do
{
input = myFile.ReadLine();
if (input != null)
{
WriteLine(input);
count++;
}
} while (input != null);
for (int i = 0; i < count; i++)
{
grades[i] = int.Parse(input);
}
You start the for loop just after exiting from the while loop. And the condition to exit from the while loop is true when input is null. Of course this is not well accepted by Int.Parse.
Instead you can use a single loop, taking in consideration that you don't want to loop more than 50 times otherwise you exceed the array dimensions
int count = 0;
while((input = myFile.ReadLine()) != null && count < 50)
{
WriteLine(input);
grades[count] = int.Parse(input);
count++;
}
However you can have a more flexible way to handle your input if you use a List<int> instead of an array of integers. In this way you don't have to check for the number of lines present in your file
List<int> grades = new List<int>();
while((input = myFile.ReadLine()) != null)
grades.Add(int.Parse(input));
if we want to get really condensed
var grades = File.ReadAllLines(path).Select(l=>Int.Parse(l)).ToArray();
Utilize the Path.Combine() to help you in concatenating paths.
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
String fullPath = Path.Combine(environment, "grades.txt");
int[] grades = File.ReadAllLines(fullPath).Select(p => int.Parse(p)).ToArray<int>();
Console.WriteLine(grades);
Refer to https://www.dotnetperls.com/file-readalllines on how to use File.ReadAllLines() its very handy.
I'm using LINQ here, which sometimes simplifies things. Even though it looks a bit intimidating now. We read all lines, the result of that is then parsed by selecting each one and converting it to an integer then outputting an array of integers and saving that to grades.
Program p = new Program();
int MAX = 50;
int[] grades = new int[MAX];
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
string path = environment + "grades.txt";
using (StreamReader myFile = new StreamReader(path))
{
string input;
int count = 0;
while((!myFile.EndOfStream) && (count < MAX))
{
input = myFile.ReadLine();
if (!String.IsNullOrWhiteSpace(input))
{
WriteLine(input);
grades[count] = int.Parse(input);
count++;
}
}
}
You should definitely use the "using" pattern around your stream object. Got rid of the for-loop for you while maintaining mostly your code and style. Your issue was that you weren't using the input value before moving on to the next line. You only ever had the last value in your original code.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Is someone able to help me out with the following please, I'm trying to split data from an input file (2 pieces of data per line, separated by either of the delimiters specified in the code below). To do this I have declared the string array 'split input', however when I run the program I get a runtime error (screenshot) with the split input line inside the while loop highlighted in yellow. I can't see what I am doing wrong, I'm copying sample code which seems to be working fine :(
NB - the messageBox line below the yellow is just for my testing to prove the split worked
private int DetermineArraySize(StreamReader inputFile)
{
int count = 0;
while (!inputFile.EndOfStream)
{
inputFile.ReadLine();
count++;
}
return count;
}
private void ReadIntoArray(StreamReader inputFile, string[] gameArray, int[] revArray)
{
string rawInput;
string[] splitInput = new string[2];
int count = 0;
char[] delimiters = {'=', '#',};
while (!inputFile.EndOfStream || count < gameArray.Length)
{
rawInput = inputFile.ReadLine();
{
splitInput = rawInput.Split(delimiters);
MessageBox.Show(splitInput[0] + " // " + splitInput[1]);
count++;
}
}
}
private void rdGameSalesForm_Load(object sender, EventArgs e)
{
StreamReader inputFile = File.OpenText("GameSales.txt"); //Open Input File
int arraySize = DetermineArraySize(inputFile); //Use input file to determine array size
string[] gameTitle = new string[arraySize]; //Declare array for GameTitle
int[] revenue = new int[arraySize]; ///Declare array for Revenue
ReadIntoArray(inputFile, gameTitle, revenue);
Thanks for your help
Just add check on null.
ReadLine Method returns null if the end of the input stream is reached. It is possible because you check !inputFile.EndOfStream or count < gameArray.Length. So in the second condition has a possibility to get null when input filre reading
while (!inputFile.EndOfStream || count < gameArray.Length)
{
rawInput = inputFile.ReadLine();
if(rawInput !=null)
{
splitInput = rawInput.Split(delimiters);
MessageBox.Show(splitInput[0] + " // " + splitInput[1]);
}
}
Check for null instead of end of stream.
while((rawInput = Inputfile.ReadLine()) != null)
{
splitInput = rawInput.Split(delimiters);
MessageBox.Show(...);
}
I've got a RichTextBox, here referred to as box.
string currentline = box.Lines[box.GetLineFromCharIndex(box.SelectionStart)];
That line there fetches the line the caret is in. It works excellently.
However, I have a need to get two strings from this. The first is everything on that line UP to the caret, and the second is everything on that line AFTER it.
For instance, if the line is How is you|r day going?, with | representing the caret, I would get How is you and r day going?, separately.
I wrote this monstrosity, which works:
string allbefore = box.Text.Substring(0, box.SelectionStart);
string allafter = box.Text.Substring(box.SelectionStart, box.Text.Length - box.SelectionStart);
string linebefore = "";
for (int i = 0; i < allbefore.Length; i++)
{
linebefore += allbefore[i];
if (allbefore[i] == '\n')
linebefore = "";
}
string lineafter = "";
for (int i = 0; i < allafter.Length; i++)
{
if (allafter[i] == '\n')
break;
else
lineafter += allafter[i];
}
It gives me the result I want, but involves looping through EVERY character in the entire box, which just hurts. Is there an easy way to do this I'm just missing? Thanks.
This might do the trick for you
string currentline = box.Lines[box.GetLineFromCharIndex(box.SelectionStart)];
var listOfStrings = new List<string>();
string[] splitedBox = currentline.Split('|');
foreach(string sp in splitedBox)
{
string[] lineleft = sp.Split('\n');
listOfStrings.Add(lineleft[lineleft.Count() - 1]);
}
In the first approach we are splitting the line by char | than finding if we have any \n if it exsist we are taking the values accordingly
Another approach could be
string box = "How is \n you|r day \n going?";
bool alllinesremoved = true;
while(alllinesremoved)
{
if(box.Contains('\n'))
{
if(box.IndexOf('\n') > box.IndexOf('|'))
{
box = box.Remove(box.IndexOf('\n'), (box.Length - box.IndexOf('\n')));
}
else
{
box = box.Remove(0, box.IndexOf('\n') + 1);
}
}
else
{
alllinesremoved = false;
}
}
string[] splitedBox = box.Split('|');
in the second approach we are removing the characters before and after the \n and then splitting the string. I think the second one seems more good to me.
Have you tried using line.split? Not sure if this is what you want.
Store the position of \n using indexOf and, if >= 0, that is, the string contains it, use substring and assign the value otherwise.
string allbefore = box.Text.Substring(0, box.SelectionStart);
string allafter = box.Text.Substring(box.SelectionStart, box.Text.Length - box.SelectionStart);
int newLinePos = allBefore.lastIndexOf("\n");
string lineBefore = ((newLinePos >= 0) ? (allBefore.substring(newLinePos + 1)) : (allBefore));
newLinePos = allafter.indexOf("\n");
string lineAfter = ((newLinePost >= 0) ? (allAfter.substring(0, newLinePos)) : (allAfter));
This question already has answers here:
Adding numbers to a string?
(5 answers)
Closed 7 years ago.
i am looping through some nodes and getting the charge and adding them together. the charge is of type string though.
first time it loops string charge = "309",
second time it loop string charge = "38";
`Looping through list of nodes
{
saBillDetail.TotalServiceUsage += totalSvcNode.InnerText;
}
`
I would have expected that I could add them together, but they are being concatenated instead like this:
`charge + charge = '30938'`
How can I force these strings to be treated as numbers? and get output like this at the end of the loop
`charge + charge = '347'`
As people allready answered this maybe another solution
So you don't get errors
private static int AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
Int32.TryParse(one, out iOne);
Int32.TryParse(two, out iTwo);
return iOne + iTwo;
}
Or if you want a string result.
private static String AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
Int32.TryParse(one, out iOne);
Int32.TryParse(two, out iTwo);
return (iOne + iTwo).ToString();
}
EDIT:
As Alexei Levenkov stated you could/should handle exceptions.
Maybe something like this will help you during development
private static int AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
bool successParseOne = Int32.TryParse(one, out iOne);
bool successParseTwo = Int32.TryParse(two, out iTwo);
if (!successParseOne)
{
throw new ArgumentException("one");
}
else if(!successParseTwo)
{
throw new ArgumentException("two");
}
return (iOne + iTwo);
}
So when you have a wrong number you will be notified if you use try/catch
You need to parse the numbers from the strings:
string number1 = "309";
string number2 = "38";
int result = int.Parse(number1) + int.Parse(number2);
Then you can set the text equal to that string representation:
string addResult = result.ToString();
Note: Int32.Parse() will throw an exception if the format isn't correct. Consider using Int32.TryParse() for a bool way to capture an impossible parsing.
You will need to convert your strings to integer, add them and convert the result back to string:
int sum = 0;
foreach (string strNumber in strNumberCollection)
{
int number;
if (int.TryParse(strNumber, out number))
sum += number;
}
string total = sum.ToString();