寻找与 scanf 等效的 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/472202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looking for C# equivalent of scanf
提问by Larry
I used to code in C language in the past and I found the scanf
function very useful.
Unfortunately, there is no equivalent in C#.
我过去用 C 语言编写代码,我发现该scanf
功能非常有用。不幸的是,在 C# 中没有等价物。
I am using using it to parse semi-structured text files.
我正在使用它来解析半结构化文本文件。
I found an interresting example of scanf
implementation here. Unfortunately, it looks old and incomplete.
我在这里找到了一个有趣的scanf
实现示例。不幸的是,它看起来很旧而且不完整。
Does anyone know a scanf
C# implementation ? Or at least something that would work as a reversed string.Format
?
有谁知道scanf
C# 实现?或者至少可以作为反向工作的东西string.Format
?
采纳答案by Jonathan Wood
If regular expressions aren't working for you, I've just posted a sscanf()
replacement for .NET. The code can be viewed and downloaded at http://www.blackbeltcoder.com/Articles/strings/a-sscanf-replacement-for-net.
如果正则表达式对您不起作用,我刚刚发布了sscanf()
.NET的替代品。可以在http://www.blackbeltcoder.com/Articles/strings/a-sscanf-replacement-for-net查看和下载代码。
回答by Mitch Wheat
Since the files are "semi-structured" can't you use a combination of ReadLine() and TryParse() methods, or the Regex class to parse your data?
由于文件是“半结构化的”,您不能结合使用 ReadLine() 和 TryParse() 方法或 Regex 类来解析您的数据吗?
回答by okutane
You can use scanf directly from C runtime libraries, but this can be difficult if you need to run it with different parameters count. I recommend you to regular expressions for you task or describe that task here, maybe there is another ways.
您可以直接从 C 运行时库中使用 scanf,但如果您需要使用不同的参数计数运行它,这可能会很困难。我建议您为您的任务使用正则表达式或在此处描述该任务,也许还有其他方法。
回答by SMB
You could use System.IO.FileStream, and System.IO.StreamReader, and then parse from there.
您可以使用 System.IO.FileStream 和 System.IO.StreamReader,然后从那里进行解析。
回答by Nichol Draper
I think you want the C# library functions either Parse or Convert.
我认为您需要 C# 库函数 Parse 或 Convert。
// here's an example of getting the hex value from a command line
// program.exe 0x00080000
static void Main(string[] args)
{
int value = Convert.ToInt32(args[1].Substring(2), 16);
Console.Out.WriteLine("Value is: " + value.ToString());
}
回答by sprite
There is good reason why a scanf like function is missing from c#. It's very prone to error, and not flexible. Using Regex is much more flexible and powerful.
c# 中缺少类似 scanf 的函数是有充分理由的。它很容易出错,而且不灵活。使用 Regex 更加灵活和强大。
Another benefit is that it's easier to reuse throughout your code if you need to parse the same thing in different parts of the code.
另一个好处是,如果您需要在代码的不同部分解析相同的内容,则可以更轻松地在整个代码中重用。
回答by jurik
I have found a better solution than using sscanf from C or some rewritten part by someone (no offence)
我找到了比使用 C 中的 sscanf 或某人重写的部分更好的解决方案(无罪)
http://msdn.microsoft.com/en-us/library/63ew9az0.aspxhave a look at this article, it explains how to make named groups to extract the wanted data from a patterned string. Beware of the little error in the article and the better version below. (the colon was not part of the group)
http://msdn.microsoft.com/en-us/library/63ew9az0.aspx看看这篇文章,它解释了如何让命名组从模式字符串中提取所需的数据。请注意文章中的小错误和下面的更好版本。(冒号不属于该组)
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string url = "http://www.contoso.com:8080/letters/readme.html";
Regex r = new Regex(@"^(?<proto>\w+)://[^/]+?(?<port>:\d+)?/",RegexOptions.None, TimeSpan.FromMilliseconds(150));
Match m = r.Match(url);
if (m.Success)
Console.WriteLine(r.Match(url).Result("${proto}:${port}"));
}
}
// The example displays the following output:
// http::8080
回答by whatsRegex
Although this looks sort of crude it does get the job done:
虽然这看起来有点粗糙,但它确实完成了工作:
// Create the stream reader
sr = new StreamReader("myFile.txt");
// Read it
srRec = sr.ReadLine();
// Replace multiple spaces with one space
String rec1 = srRec.Replace(" ", " ");
String rec2 = rec1.Replace(" ", " ");
String rec3 = rec2.Replace(" ", " ");
String rec4 = rec3.Replace(" ", " ");
String rec5 = rec4.Replace(" ", " ");
String rec6 = rec5.Replace(" ", " ");
String rec7 = rec6.Replace(" ", " ");
String rec8 = rec7.Replace(" ", " ");
String rec9 = rec8.Replace(" ", " ");
// Finally split the string into an array of strings with Split
String[] srVals = rec9.Split(' ');
You can then use the array srVals as individual variables from the record.
然后,您可以将数组 srVals 用作记录中的单个变量。
回答by Jason Lee
Try importing msvcrt.dll
尝试导入 msvcrt.dll
using System.Runtime.InteropServices;
namespace Sample
{
class Program
{
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int printf(string format, __arglist);
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int scanf(string format, __arglist);
static void Main()
{
int a, b;
scanf("%d%d", __arglist(out a, out b));
printf("The sum of %d and %d is %d.\n", __arglist(a, b, a + b));
}
}
}
which works well on .NET Framework. But on Mono, it shows the error message:
在 .NET Framework 上运行良好。但是在 Mono 上,它显示了错误消息:
Unhandled Exception:
System.InvalidProgramException: Invalid IL code in Sample.Program:Main (): IL_0009: call 0x0a000001
[ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidProgramException: Invalid IL code in Sample.Program:Main (): IL_0009: call 0x0a000001
If you need Mono compatibility, you need to avoid using arglist
如果需要 Mono 兼容性,则需要避免使用 arglist
using System.Runtime.InteropServices;
namespace Sample
{
class Program
{
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int printf(string format, int a, int b, int c);
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int scanf(string format, out int a, out int b);
static void Main()
{
int a, b;
scanf("%d%d", out a, out b);
printf("The sum of %d and %d is %d.\n", a, b, a + b);
}
}
}
in which the number of arguments is fixed.
其中参数的数量是固定的。
Edit 2018-5-24
编辑 2018-5-24
arglist
doesn't work on .NET Core either. It seems that calling the C vararg function is deprecated. You should use the .NET string API such as String.Format
instead.
arglist
也不适用于 .NET Core。似乎不推荐调用 C vararg 函数。您应该改用 .NET 字符串 API String.Format
。