I Have a string array with 5 values, i want the program to loop even though i don't enter a value for the arrays. If I split the arrays without inserting anything (pressing ..... (5 times "." to split the array) then it doesn't crash it will just loop. But if i just hit enter, then the program crashes.
Is there a way to fix the loop so that even though there is no kind of input, that it won't crash? (It also crashes if you don't complete all 5 values.)
Net = Console.ReadLine();
string[] oktet = new string[5];
oktet = Net.Split('.', '/');
temp = oktet[0]; //inputs value of array in temp
NaN = int.TryParse(temp, out Net0);
temp = oktet[1];
NaN = int.TryParse(temp, out Net1);
temp = oktet[2];
NaN = int.TryParse(temp, out Net2);
temp = oktet[3];
NaN = int.TryParse(temp, out Net3);
temp = oktet[4];
NaN = int.TryParse(temp, out subnet);
}
while (!NaN | Net0 > 255 | Net0 < 0 | Net1 > 255 | Net1 < 0 | Net2 > 255 | Net2 < 0 | Net3 > 255 | Net3 < 0 | subnet > 32 | subnet < 0);
I know it's pretty amateur, but hey, we're here to learn right? :)
Thanks in advanced!
You can try to do something like this:
string[] oktet = Net.Split('.', '/'); // size array according to input
if (oktet.Length != 5) continue; // reloop on bad input
Those two lines of code replace these:
string[] oktet = new string[5];
oktet = Net.Split('.', '/');
I would just use some command line option library if you could (unless this is homework where you need to learn how to validate input, parse, etc.). See NDesk.Options (http://www.ndesk.org/Options), available via Nuget as well. See the following for required options: How to enforce required command-line options with NDesk.Options?
var userInput = Console.ReadLine();
var userInputSplit = userInput.Split('.', '/');
var numbers = userInputSplit.Select(word =>
{
int result;
if (byte.TryParse(word, out result))
return (byte?)result;
return (byte?)null; });
});
var inputComplete = number.Where(number => number.HasValue).Count() == 4;
The problem is that your variable oktet isn't an array of 5, because you're assigning something else in it.
string[] oktet = new string[5]; // Assigns an array of 5
oktet = Net.Split('.', '/'); //assigns the result of the split to the variable
So, oktet is has the result of the split, and its length.
BTW, Classes start with a capital letter, and the variables should start with a small letter.
Coding standards will make the code more readable, and will help you tell the difference between items.
Related
I am attempting to read a log file in this format:
date | cost
date | cost
..ect
Using the following code to read the file in to an array:
string[] lines = File.ReadAllLines("log.txt");
My question is how do I slice the array in to 2 parts per line so that I can add them to a list view of 2 columns? I was thinking perhaps a dictionary would be a good start..
Assuming this is C# rather than C, the following may do what you're looking for:
public class LogEntry{
public string Date;
public string Cost;
public LogEntry(string date,string cost){
Date=date;
Cost=cost;
}
}
...
// Grab the lines from the file:
string[] lines = File.ReadAllLines("log.txt");
// Create our output set:
LogEntry[] logEntries=new LogEntry[lines.Length];
// For each line in the file:
for(int i=0;i<lines.Length;i++){
// Split the line:
string[] linePieces=lines[i].Split('|');
// Safety check - make sure this is a line we want:
if(linePieces.Length!=2){
// No thanks!
continue;
}
// Create the entry:
logEntries[i]=new LogEntry( linePieces[0] , linePieces[1] );
}
// Do something with logEntries.
Note that this sort of processing should only be done with a relatively small log file. File.ReadAllLines("log.txt") becomes very inefficient with large files, at which point using a raw FileStream is more suitable.
var lines = File.ReadAllLines("log.txt").Select(l=> l.Split('|'));
var dictionary= lines.ToDictionary(x => x[0], y => y[1]);
Use a 2D array and string.Split('-')
string[] lines = File.ReadAllLines("log.txt");
//Create an array with lines.Length rows and 2 columns
string[,] table = new string[lines.Length,2];
for (int i = 0; i < lines.Length; i++)
{
//Split the line in 2 with the | character
string[] parts = lines[i].Split('|');
//Store them in the array, trimming the spaces off
table[i,0] = parts[0].Trim();
table[i,1] = parts[1].Trim();
}
Now you will have an array that looks like this:
table[date, cost]
You could use a dictionary so you only have to look up the date if you want to improve it. EDIT: As #Damith has done
Additionally, with LINQ you could simplify this into:
var table = File.ReadAllLines("log.txt").Select(s => s.Split('|')).ToDictionary(k => k[0].TrimEnd(' '), v => v[1].TrimStart(' '));
Which you can now easily get the results from the LINQ expression with:
foreach (KeyValuePair<string, string> kv in table)
{
Console.WriteLine("Key: " + kv.Key + " Value: " + kv.Value);
}
Also note if you do not need the spaces in your file you can omit the Trim()s
And just because this post was originally tagged C :)
Here is a C example:
With a data file (I called it temp.txt) that looks like this:
3/13/56 | 13.34
3/14/56 | 14.14
3/15/56 | 15.00
3/16/56 | 16.56
3/17/56 | 17.87
3/18/56 | 18.34
3/19/56 | 19.31
3/20/56 | 20.01
3/21/56 | 21.00
This code will read it, parse it into a single 2 dim string array, char col[2][80][20];
#include <ansi_c.h>
int main()
{
int i;
char *buf;
char line[260];
char col[2][80][20];
FILE *fp;
fp = fopen("c:\\dev\\play\\temp.txt", "r");
i=-1;
while(fgets(line, 260, fp))
{
i++;
buf = strtok(line, "|");
if(buf) strcpy(col[0][i], buf);
buf = strtok(NULL, "|");
if(buf) strcpy(col[1][i], buf);
}
fclose(fp);
return 0;
}
Let's say I have text file like this
<pre>----------------
hPa m C
---------------------
1004.0 28 13.6
1000.0 62 16.2
998.0 79 17.2
992.0 131 18.0
<pre>----------------
Sometext here
1000.0 10 10.6
1000.0 10 11.2
900.0 10 12.2
900.0 100 13.0
<aaa>----------------
How Can I Create Array in C# that reads text file from line number 5 (1004.0) to just before line that starts with string <pre>-
I used string[] lines = System.IO.File.ReadAllLines(Filepath);
To make each line in the array
The problem is I want only numbers of first section in the array in order to separate them later to another 3 arrays (hPa, m, C) .
Here's a possible solution. It's probably way more complicated than it should be, but that should give you an idea of possible mechanisms to further refine your data.
string[] lines = System.IO.File.ReadAllLines("test.txt");
List<double> results = new List<double>();
foreach (var line in lines.Skip(4))
{
if (line.StartsWith("<pre>"))
break;
Regex numberReg = new Regex(#"\d+(\.\d){0,1}"); //will find any number ending in ".X" - it's primitive, and won't work for something like 0.01, but no such data showed up in your example
var result = numberReg.Matches(line).Cast<Match>().FirstOrDefault(); //use only the first number from each line. You could use Cast<Match>().Skip(1).FirstOrDefault to get the second, and so on...
if (result != null)
results.Add(Convert.ToDouble(result.Value, System.Globalization.CultureInfo.InvariantCulture)); //Note the use of InvariantCulture, otherwise you may need to worry about , or . in your numbers
}
Do you mean this?
System.IO.StreamReader file = new System.IO.StreamReader(FILE_PATH);
int skipLines = 5;
for (int i = 0; i < skipLines; i++)
{
file.ReadLine();
}
// Do what you want here.
I have a program written in Delphi is converting 11 to 0xB and 28 to 0x1c. I tried to convert 11 (decimal to Hex) in c# using this:-
var deciValue01 = 11;
var deciValue02 = 28;
var deciValue03 = 13;
System.Diagnostics.Debug.WriteLine(string.Format("11 = {0:x}", deciValue01));
System.Diagnostics.Debug.WriteLine(string.Format("28 = {0:x}", deciValue02));
System.Diagnostics.Debug.WriteLine(string.Format("13 = {0:x}", deciValue03));
but the results I am getting is:-
11 = b
28 = 1c
13 = d
Wondering how to convert 11 to '0xB' and 28 to '0x1c' and 13 to '0xD'? Isn't it I need to change from Decimal to Hex?
You just need to use X to make it capital hex digits instead of lower case, and add the 0x yourself:
// Add using System.Diagnostics; at the top of the file... no need to
// explicitly qualify all your type names
Debug.WriteLine(string.Format("11 = 0x{0:X}", deciValue01));
Debug.WriteLine(string.Format("28 = 0x{0:X}", deciValue02));
Debug.WriteLine(string.Format("13 = 0x{0:X}", deciValue03));
Note that the deciValue01 values are neither "decimal" nor "hex" themselves. They're just numbers. The concept of "decimal" or "hex" only makes sense when you're talking about a textual representation, at least for integers. (It matters for floating point, where the set of representable types depends on the base used.)
Try This
int value = Convert.ToInt32(/*"HexValue"*/);
String hexRepresentation = Convert.ToString(value, 16);
It sounds like you want this...
var deciValue01 = 11;
var deciValue02 = 28;
var deciValue03 = 13;
System.Diagnostics.Debug.WriteLine(string.Format("11 = 0x{0:x}", deciValue01));
System.Diagnostics.Debug.WriteLine(string.Format("28 = 0x{0:x}", deciValue02));
System.Diagnostics.Debug.WriteLine(string.Format("13 = 0x{0:x}", deciValue03));
hi i'm trying to extract values from this tagged file
here is the file
0
LINE
5
1C1CBD
330
1C1ADB
100
AcDbEntity
8
0-FD
62
9
370
-2
100
AcDbLine
10
53740.73468153231
20
-190253.3098529756
30
0.0
11
53690.49919802765
21
-190166.2994431953
31
0.0
0
you can see that there is a hexadecimal number below "LINE", is there anyway i can extract it into some list?
like
VALUE = 1C1CBD
NOTE: the file consist more than one of this kind of pattern
and then how can i get the maximum value?
EDIT 1
i see that "5" can be found by using regex "\s\s5" can i use this?
Thank you for your feedback i have been able to complete what i want
here is the code
string[] handle = originalString.Split(new string[] { "\r\n" }, StringSplitOptions.None);
List<string> hexa = new List<string>();
for (var a = 1; a <= handle.Count() - 1; a++)
{
if (Regex.IsMatch(handle[a], #"^\s\s5"))
{
hexa.Add(handle[a + 1]);
}
}
List<int> HexaToInt = new List<int>();
foreach (string valueHexa in hexa)
{
int intHexaValue = int.Parse(valueHexa, System.Globalization.NumberStyles.HexNumber);
HexaToInt.Add(intHexaValue);
}
int maximumHexa = HexaToInt.Max();
string hexValue = maximumHexa.ToString("X");
it is possible afterall to extract the hexadecimal value from the handle group codes
It is totally impossible.
No way to catch characters and extract what you need.
You have to organize the structure of this file better.
Is there any way to do integer incremental replacement only with regex.
Here is the problem, I have text file containing 1 000 000 lines all starting with %
I would like to have replace # by integer incrementally using regex.
input:
% line one
% line two
% line three
...
output:
1 line one
2 line two
3 line three
...
n = 1
with open('sourcefile.txt') as input:
with open('destination.txt', 'w') as output:
for line in input:
if line.startswith('%'):
line = str(n) + line[1:]
n += 1
output.write(line)
Here's a way to do it in Python
import re
from itertools import count
s="""
% line one
% line two
% line three"""
def f():
n=count(1)
def inner(m):
return str(next(n))
return inner
new_s = re.sub("%",f(),s)
alternatively you could use a lambda function in there like so:
new_s = re.sub("%",lambda m,n=count(1):str(next(n)),s)
But it's easy and better to skip regexp altogether
from __future__ import print_function # For Python<3
import fileinput
f=fileinput.FileInput("file.txt", inplace=1)
for i,line in enumerate(f):
print ("{0}{1}".format(i, line[1:]), end="")
Since all the lines start with "%" there is no need to even look at that first char
Although this problem would best be solved by reading the file line by line and checking the first character with simple string functions, here is how you would do incremental replacement on a string in java:
Pattern p = Pattern.compile("^%");
Matcher m = p.matcher(text);
StringBuffer sb = new StringBuffer();
int i = 0;
while (m.find()) {
m.appendReplacement(sb, String.valueOf(i++));
}
m.appendTail(sb);
return sb.toString();
in python re.sub accept function as parameter see http://docs.python.org/library/re.html#re.sub
Depending on your choice of language (you've listed a few) PHP's preg_replace_callback() might be an appropriate function to use
$text = "% First Line\n% Second Line\n% Third Line";
function cb_numbers($matches)
{
static $c = 1;
return $c++;
}
$text = preg_replace_callback(
"/(%)/",
"cb_numbers",
$text);
echo $text;
Here's a C# (3.0+) version:
string s = "% line one\n% line two\n% line three";
int n = 1;
s = Regex.Replace(s, #"(?m)^%", m => { return n++.ToString(); });
Console.WriteLine(s);
output:
1 line one
2 line two
3 line three
Of course it requires the whole text to be loaded into memory. If I were doing this for real, I'd probably go with a line-by-line approach.
And a PHP version for good measure:
$input = #fopen('input.txt', 'r');
$output = #fopen("output.txt", "w");
if ($input && $output) {
$i = 0;
while (!feof($input)) {
$line = fgets($input);
fputs($output, ($line[0] === '%') ?
substr_replace($line, ++$i, 0, 1) :
$line
);
}
fclose($input);
fclose($output);
}
And just because you can, a perl one-liner (yes, with a regex):
perl -i.bak -pe 'BEGIN{$i=1} (s/^%/$i/) && $i++' input.txt
import re, itertools
counter= itertools.count(1)
replacer= lambda match: "%d" % counter.next()
text= re.sub("(?m)^%", replacer, text)
counter is… a counter :). replacer is a function returning the counter values as strings. The "(?m)^%" regex is true for every % at the start of a line (note the multi-line flag).