How do i input integers from a file into a vector3 or a int variable?
This is my code what works for only string
using (var enviromentPos = new FileStream("enviromentPos.txt", FileMode.OpenOrCreate))
{
using(var input = new StreamReader(enviromentPos))
{
int line = "";
while ((line = input.ReadLine()) != null)
{
}
}
}
String line="";
List<int> foo = new List<int>()
while ((line = input.ReadLine()) != null)
{
int i=0;
if(int.TryParse(line,out i)) foo.Add(i);
}
will read line by line and add all lines which contain something int-parseable to the list as parsed int values
Once you have the code that reads your input:
String line = null;
var input = new List<int>();
while ((line = file.ReadLine()) != null)
{
int i = 0;
if( int.TryParse(line,out i))
{
input.Add(i);
}
}
You can either process the list afterwards:
var vectors = new List<Vector3>();
for (int index = 0; index < input.Count; index += 3)
{
vectors.Add(new Vector3(input[index], input[index+1], input[index+2]);
}
You would need to make sure that the input was a multiple of three by either truncating it or padding it.
Or you could process the input as you are reading, but then you'd need a counter so that you could execute the vectors.Add code every third value read from the file:
String line = null;
var input = new List<int>();
int count = 0;
var vectors = new List<Vector3>();
while ((line = file.ReadLine()) != null)
{
int i = 0;
if( int.TryParse(line,out i))
{
input.Add(i);
count++;
if (count % 3 == 0)
{
vectors.Add(new Vector3(input[count-2], input[count-1], input[count]);
}
}
}
Related
I am writing a program in C# to read from a file and output to a csv file all of the unique words and the number of occurrences in the file for each word. My issue is when I try to run my program, I never get out of my while loop that goes line by line.
public override List<WordEntry> GetWordCount()
{
List<WordEntry> words = new List<WordEntry>();
WordEntry wordEntry = new WordEntry();
//string[] tokens = null;
string line, temp, getword;
int count = 0, index = 0;
long number;
while ((line = input.ReadLine()) != null)
{
if (line == null)
Debug.Write("shouldnt happen");
char[] delimit = { ' ', ',' };
string[] tokens = line.Split(delimit);
if (words.Count == 0)
{
wordEntry.Word = tokens[0];
wordEntry.WordCount = 1;
words.Add(wordEntry);
}//end if
for (int i = 0; i < tokens.Length; i++)
{
for (int j = 0; j < words.Count; j++)
{
if (tokens[i] == words[j].Word)
{
number = words[j].WordCount;
number++;
getword = words[j].Word;
wordEntry.WordCount = number;
wordEntry.Word = getword;
words.RemoveAt(j);
words.Insert(j, wordEntry);
}//end if
else
{
wordEntry.Word = tokens[i];
wordEntry.WordCount = 1;
words.Add(wordEntry);
}//end else
}//end for
}//end for
}//end while
return words;
}
It is getting stuck in the while loop as if it never reaches the end of the file. The file is 2.6 MB so it should be able to make it to the end.
Here's how you can rewrite your code to use a dictionary.
var words = new Dictionary<string,int>();
while ((line = input.ReadLine()) != null)
{
if (line == null)
Debug.Write("shouldnt happen");
char[] delimit = { ' ', ',' };
string[] tokens = line.Split(delimit);
foreach (var word in tokens)
{
if(words.ContainsKey(word))
words[word]++;
else
words.Add(word, 1);
}
}
This reduces the complexity of the code because dictionary has a O(1) lookup.
EDIT
You can convert the dictionary into List<WordEntry> like this.
return words
.Select(kvp => new WorkEntry
{
Word = kvp.Key,
WordCount = kvp.Value
})
.ToList();
I guess in fact your code doesn't get out of the "for (int j = 0; j < words.Count; j++)" because new items are kept being added to the words list.
i have a text file like that :
; "one"
id_number:*=344E6F4D6F7265486178785454332100
; "two"
id_number:*=3536336A775E3825246E773543563437
; "three"
id:_number*=BDBD2EB72D82473DBE09F1B552A8983
and lots the same way and what i want to search in the file for the the title (two) and after that it's give me the id_number of it and i want to put the id_number in textbox
i used
string[] s = File.ReadAllLines("MyFilePath.txt");
List<byte[]> byteArrays = new List<byte[]>();
foreach (string st in s.Where(x => x.Trim().StartsWith("id_number:*=")).Select(x => x.Skip(12)))
{
byte[] b = new byte[(int)((st.Length + 1) / 2)];
for (int i = 0; i < (int)((st.Length + 1) / 2); i++)
{
var byteString = (st.Skip(2 * i).length > 2) ? st.Skip(2 * i).Take(2) : "0" + st.Skip(2 * i);
var bt = Convert.ToByte(byteString, 16);
b[i] = bt;
}
byteArrays.Add(b);
but it doesn't work
const string f = #"C:\test.txt";
static void Main(string[] args)
{
// 1
// Declare new List.
List<string> lines = new List<string>();
// 2
// Use using StreamReader for disposing.
using (StreamReader r = new StreamReader(f))
{
// 3
// Use while != null pattern for loop
string line;
while ((line = r.ReadLine()) != null)
{
// 4
// Insert logic here.
// ...
// "line" is a line in the file. Add it to our List.
if (line.Trim() == "")
continue;
lines.Add(line);
}
}
// 5
string stringValue = "two";
int correctIndex = -1;
// Print out all the lines.
for (int i=0; i<lines.Count; i++)
{
if (lines[i].Contains(stringValue))
{
correctIndex = i;
}
}
if(correctIndex == -1)
{
Console.WriteLine("item is not found");
}
else
{
//here you will need probably little more cleaning of the string. If the strings are on 1 line you should search for lines[correctIndex]
Console.WriteLine(lines[correctIndex + 1]);
}
}
}
EDIT: I don't see your edit, check if my solution helps you. Write me a comment if you want to continue with your solution.
Here this should work. Hope this helps you.
string s, result;
bool bl = false;
using (StreamReader sr = new StreamReader("....txt"))
{
while ((s = sr.ReadLine()) != null)
{
if(s.Contains ("two"))
{
bl = true;
}
if (s.Contains("id_number") && bl == true)
{
result = s.Replace("id_number:*=", "");
textBox1.Text = result;
break;
}
}
}
I am new to C#. I have been trying to read in a dataset with missing data. After reading in the headers, I read in the rest of the file using:
List<int> idList = new List<int>();
List<int[]> valList = new List<int[]>();
string line = sr.ReadLine();
while (line != null)
{
string[] lineParts = line.Split(delimiters);
int id = Convert.ToInt32(lineParts[0]);
idList.Add(id);
int[] vals = new int[numTests];
for (int i = 0; i < numTests; i++)
{
vals[i] = Convert.ToInt32(lineParts[i + 1]);
}
valList.Add(vals);
line = sr.ReadLine();
}
childIDs = idList.ToArray();
int[][] values = valList.ToArray();
When I run this, I get the error message "Input string was not in a correct format." I can't quite figure out how to read in the missing data. Any suggestions? Thanks
"Input string not in the correct format" means you're trying to parse an int from a nonsense string.
For example:
Convert.ToInt32("the letter q"); // this will throw that exception.
You could use nullable integers to track whether there was missing data. Also, consider using int.TryParse instead of Convert.ToInt32 to avoid the InvalidFormatException. Example:
List<int> idList = new List<int>();
List<int?[]> valList = new List<int?[]>();
string line;
while (null != (line = sr.ReadLine()))
{
string[] lineParts = line.Split(delimiters);
int id = Convert.ToInt32(lineParts[0]);
idList.Add(id);
int?[] vals = new int?[numTests];
for (int i = 0; i < numTests; i++)
{
int parsed;
if (!int.TryParse(lineParts[i + 1], out parsed))
vals[i] = null;
else
vals[i] = parsed;
}
valList.Add(vals);
line = sr.ReadLine();
}
childIDs = idList.ToArray();
var values = valList.ToArray();
A tab delimited txt file is being read line by line into a list of strings. the aim is to process each word of the string with the format type of the string like datetime or, float or string of characters etc.? so that the data can be plotted . Is there any other efficient way to do this?
using (StreamReader file = new StreamReader(#"C:\Users\\Desktop\snpprivatesellerlist.txt"))
{
while ((line = file.ReadLine()) != null)
{
char[] delimiters = new char[] { '\n' };
string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
st = parts[i];
// process the line - if part[i] is date time - do something ()
// if part[i] is a float - do something else()
}
}
}
Any help and insight is appreciated.
Thanks.
I would suggest using TryParse, like so...
string line;
using (StreamReader file = new StreamReader(#"C:\Users\Desktop\snpprivatesellerlist.txt"))
{
while ((line = file.ReadLine()) != null)
{
string st;
DateTime dtPart;
float flPart;
char[] delimiters = new char[] { '\n' };
string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
st = parts[i];
if (DateTime.TryParse(st, out dtPart))//Is of type DateTime
{
//Do something with DateTime dtPart
}
else if (float.TryParse(st, out flPart))//Is of type float
{
//Do something with float flPart
}
else//Can be considered a string
{
//Do something with string st
}
}
}
}
If the Fields that come in your tab-delimited file are of the same type always, and no.of fields are fixed.
Then you can create a class of structure to store each line value.
class LineData
{
public float a {get; set;}
public DateTime b {get; set;}
}
In the method implementation (i.e. in the while):
string[] parts = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
//You know 1st column is float, 2nd column is datetime
var dt = new LineData();
float.TryParse(parts[0], out dt.a);
DateTime.TryParse(parts[1], out dt.b);
//...
//store dt in a list/array. (not shown here)
The code that kinda solved my issue - but i am still working it.
using (StreamReader file = new StreamReader(#"C:\Users\Desktop\snpprivatesellerlist.txt"))
{
while ((line = file.ReadLine()) != null)
{
char[] delimiter1 = new char[] { '\n' };
string[] part1 = line.Split(delimiter1, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < part1.Length; i++)
{
sepList.Add(part1[i]);
//st = part1[i];
}
}
file.Close();
}
char[] delimiter2 = new char[] { '\t' };
for (int j = 4; j < sepList.Count; j++)
{
st = sepList[j];
string[] part2 = st.Split(delimiter2, StringSplitOptions.RemoveEmptyEntries);
alist.Add(part2);
}
//DateTime time = new DateTime();
//float value = new float();
string tagname = alist[0][0];
for (int y = 0; y < alist.Count; y++)
{
if (alist[y][0]==tagname)
{
alist1.Add(alist[y]);
}
else
{
SensorProbeDataContainer sensorprobe = new SensorProbeDataContainer();
sensorprobe.Setdata(templist);
sensorprobe.SensorProbe = sensorprobe.data[0][0];
ProbeList.Add(sensorprobe.SensorProbe);
DateTime.TryParse(sensorprobe.data[0][2], out sensorprobe.StartDate);
DateTime.TryParse(sensorprobe.data[(sensorprobe.data.Count - 1)][2], out sensorprobe.EndDate);
classcontainer.Add(sensorprobe);
tagname = alist[y][0];
templist.Clear(); }
}
I am trying to follow it on this thread - https://stackoverflow.com/questions/10719396/iterating-separating-list-of-string-arrays-based-on-first-element
Thanks all for the help. Please do point out if you spot any mistakes in code.
Okay so I've managed to read in a .txt file... now I'm trying to figure the best way to convert this information into a 2D array.
My text file (first two number provide height and width):
5
5
0,0,0,0,0
0,0,0,0,0
0,0,1,0,0
0,1,1,1,0
1,1,1,1,1
My C# / XNA:
string fileContents = string.Empty;
try
{
using (StreamReader reader = new StreamReader("Content/map.txt"))
{
fileContents = reader.ReadToEnd().ToString();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Now what I need to do next is define the size of the 2-dimensional map array and then populate the entry values... this is where I'm getting a bit stuck and have found various ways I can loop through the data but I don't think any of them have been terribly tidy.
What I've tried to do is have one loops which splits by newline... and then another loop which splits by comma delimiter.
Is this the best way to do it... or are there better alternatives?
It can be done with LINQ but that is only practical when you want (accept) an array-of-array, int[][] instead of a straight 2-dimensional int[,] .
int[][] data =
File.ReadLines(fileName)
.Skip(2)
.Select(l => l.Split(',').Select(n => int.Parse(n)).ToArray())
.ToArray();
The code below doesn't require the first to rows in your sample .CSV file:
5
5
I'd prefer it this way, but as a consequence, the code below reads the file twice. It would take a small modification use the first two rows in your sample instead.
private int[,] LoadData(string inputFilePath)
{
int[,] data = null;
if (File.Exists(inputFilePath))
{
Dictionary<string, int> counts = GetRowAndColumnCounts(inputFilePath);
int rowCount = counts["row_count"];
int columnCount = counts["column_count"];
data = new int[rowCount, columnCount];
using (StreamReader sr = File.OpenText(inputFilePath))
{
string s = "";
string[] split = null;
for (int i = 0; (s = sr.ReadLine()) != null; i++)
{
split = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < columnCount; j++)
{
data[i, j] = int.Parse(split[j]);
}
}
}
}
else
{
throw new FileDoesNotExistException("Input file does not exist");
}
return data;
}
private Dictionary<string, int> GetRowAndColumnCounts(string inputFilePath)
{
int rowCount = 0;
int columnCount = 0;
if (File.Exists(inputFilePath))
{
using (StreamReader sr = File.OpenText(inputFilePath))
{
string[] split = null;
int lineCount = 0;
for (string s = sr.ReadLine(); s != null; s = sr.ReadLine())
{
split = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (columnCount == 0)
{
columnCount = split.Length;
}
lineCount++;
}
rowCount = lineCount;
}
if (rowCount == 0 || columnCount == 0)
{
throw new FileEmptyException("No input data");
}
}
else
{
throw new FileDoesNotExistException("Input file does not exist");
}
Dictionary<string, int> counts = new Dictionary<string, int>();
counts.Add("row_count", rowCount);
counts.Add("column_count", columnCount);
return counts;
}
Here's the solution I've come up with which appears to work.
int[,] txtmap;
int height = 0;
int width = 0;
string fileContents = string.Empty;
try
{
using (StreamReader reader = new StreamReader("Content/map.txt"))
{
fileContents = reader.ReadToEnd().ToString();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
string[] parts = fileContents.Split(new string[] { "\r\n" }, StringSplitOptions.None);
for (int i = 0; i < parts.Length; i++)
{
if (i == 0)
{
// set width
width = Int16.Parse(parts[i]);
}
else if (i == 1)
{
// set height
height = Int16.Parse(parts[i]);
txtmap = new int[width, height];
}
if (i > 1)
{
// loop through tiles and assign them as needed
string[] tiles = parts[i].Split(new string[] { "," }, StringSplitOptions.None);
for (int j = 0; j < tiles.Length; j++)
{
txtmap[i - 2, j] = Int16.Parse(tiles[j]);
}
}
}