static void Main(string[] args)
{
//read in the file
StreamReader convert = new StreamReader("../../convert.txt");
//define variables
string line = convert.ReadLine();
int conversion;
int numberIn;
float conversionFactor;
Console.WriteLine("Enter the conversion in the form (amount,from,to)");
String inputMeasurement = Console.ReadLine();
string[] inputMeasurementArray = inputMeasurement.Split(',');
while (line != null)
{
string[] fileMeasurementArray = line.Split(',');
if (fileMeasurementArray[0] == inputMeasurementArray[1])
{
if (fileMeasurementArray[1] == inputMeasurementArray[2])
{
Console.WriteLine("{0}", fileMeasurementArray[2]);
}
}
line = convert.ReadLine();
//convert to int
numberIn = Convert.ToInt32(inputMeasurementArray[0]);
conversionFactor = Convert.ToInt32(fileMeasurementArray[2]);
conversion = (numberIn * conversionFactor);
}
Console.ReadKey();
}
在conversionFactor = Convert.ToInt32(fileMeasurementArray[2]);
行上,我收到错误消息“输入字符串格式不正确”。请帮忙!
文本文件包含以下内容:
ounce,gram,28.0
pound,ounce,16.0
pound,kilogram,0.454
pint,litre,0.568
inch,centimetre,2.5
mile,inch,63360.0
答案 0 :(得分:2)
根据文本文件的行,fileMeasurementArray[2]
将为28.0 pound
。这不能转换为int。您应该删除字符串并仅保留数字28.0
。
更新:问题已更新,文本文件行已更正。所以我以前的回答再也没有意义了。
问题可能是因为您尝试将float转换为int。
答案 1 :(得分:2)
您正在尝试将float转换为int。
将conversionFactor定义为double
变量转换也需要是双倍的。
喜欢这样
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace measurementConverter {
class Program
{
static void Main(string[] args)
{ //read in the file
StreamReader convert = new StreamReader("../../convert.txt");
//define variables
string line = convert.ReadLine();
double conversion;
int numberIn;
double conversionFactor;
Console.WriteLine("Enter the conversion in the form (amount,from,to)");
String inputMeasurement = Console.ReadLine();
string[] inputMeasurementArray = inputMeasurement.Split(',');
while (line != null)
{
string[] fileMeasurementArray = line.Split(',');
if (fileMeasurementArray[0] == inputMeasurementArray[1])
{
if (fileMeasurementArray[1] == inputMeasurementArray[2])
{
Console.WriteLine("{0}", fileMeasurementArray[2]);
}
}
line = convert.ReadLine();
//convert to int
numberIn = Convert.ToInt32(inputMeasurementArray[0]);
conversionFactor = Convert.ToDouble(fileMeasurementArray[2]);
conversion = (numberIn * conversionFactor);
}
Console.ReadKey();
}
}
}
答案 2 :(得分:0)
'28 .0 pound'不是整数。我想这就是你的问题所在。
答案 3 :(得分:0)
numberIn
和conversionFactor
是花车,而不是Ints。使用:
float numberIn;
float conversionFactor;
...
//convert to float
numberIn = Convert.ToSingle(inputMeasurementArray[0]);
conversionFactor = Convert.ToSingle(fileMeasurementArray[2]);