【问题标题】:Converting to int [duplicate]转换为 int [重复]
【发布时间】:2020-05-13 19:02:05
【问题描述】:

当我尝试将从文本文件读取的字符串变量转换为 int 时遇到错误。 如何将从文本读取的数字转换为 int?

namespace ConsoleApp1
{
    class FileWriter
    {
        static void Main()
        {
            int a = 6;
            StreamWriter writer = new StreamWriter(@"D:\asd.txt");
            using (writer)
            {
               writer.WriteLine(a);
            }
        }
    }
}
class FileReader
{
     static void Second()
     {
        StreamReader reader = new StreamReader(@"D:\asd.txt");
        using (reader)
        {

            string line = reader.ReadLine();
            Console.WriteLine(line);

           }

            );

    }

    }

【问题讨论】:

  • 同时上传您遇到的错误。将来,它可以帮助人们(我们)了解问题所在。在这种情况下,文件的格式也很重要。所以也许尝试更新你的问题。
  • 请编辑您的代码,使其可读和可编译
  • 这能回答你的问题吗? How can I convert String to Int?
  • 查看注释:将readerwriter 初始化为using 块的一部分,而不是在它之前。

标签: c#


【解决方案1】:

你使用Int32.TryParse是安全的

【讨论】:

    【解决方案2】:

    您可以尝试这样的操作,使用 TryParseTrim() 删除所有空格。

    class FileReader
    {
        static void Second()
        {
            StreamReader reader = new StreamReader(@"D:\asd.txt");
    
            using(reader)
            {
                int number;
                string line = reader.ReadLine();
                bool success = Int32.TryParse(value.Trim(), out number);
                if (success) {
                    Console.WriteLine("Number is:" + number);
                } else {
                    Console.WriteLine("Could not parse the number");
                }
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用下面代码中提到的Int32.TryParse

       int no = 0;
       string number = "6";
       Int32.TryParse(number, out no);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-03
        • 2012-08-22
        • 2016-08-24
        • 2015-04-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多