c# - Cannot convert from 'System.IO.FileStream' to 'int' when reading text file into a List -
this question has answer here:
all want have program read .txt file, take whatever in file, , input list. tell me can't convert (no matter if set variable var, string, int, or whatever) tried using int.tryparse, convert.toint32(), etc. while convert.toint32 shuts up, when run program crashes.
static void main(string[] args) { string listpath = @"k:\listdata\listdata.txt"; int listdatasum = 0; int listdatamax = 0; int listdatamin = 0; string userinput = null; var numerallistdata = system.io.file.openread(listpath); var listdata = new list<int>(numerallistdata); listdatasum = listdata.sum(); listdatamax = listdata.max(); listdatamin = listdata.min(); console.writeline( "please input data wish see, type 'help' type"); userinput = console.readline(); userinput.tolower(); if (userinput == "sum") { console.writeline("the sum of list " + listdatasum); }
edit: if question duplicate, please send link, tried search function , other questions way complicated little experience me understand.
if trying read integers file, min, max , sum want read each line array of strings, try , convert each string int , add list.
static void main(string[] args) { string listpath = @"k:\listdata\listdata.txt"; int listdatasum = 0; int listdatamax = 0; int listdatamin = 0; string userinput = null; var filereader = new system.io.streamreader(listpath); list<string> stringsfromfile = new list<string>(); string lineoftext; while ((lineoftext = filereader.readline()) != null) { stringsfromfile.add(lineoftext); } list<int> intsfromfile = new list<int>(); foreach(string s in stringsfromfile) { int temp = 0; if(int32.tryparse(s, out temp)) { intsfromfile.add(temp); } } listdatasum = intsfromfile.sum(); listdatamax = intsfromfile.max(); listdatamin = intsfromfile.min(); console.writeline("please input data wish see, type 'help' type"); userinput = console.readline(); userinput.tolower(); if (userinput == "sum") { console.writeline("the sum of list " + listdatasum); } }
Comments
Post a Comment