[英]How can i read numbers from a file
乍一看,这可能是一个愚蠢的问题,但我真的被困住了,而且很着急……我有一个文件,该文件包含一个文件中存储的 X 个数字。 我可以通过这种方式在文件中存储数字
22 56 102 9 302
在一个单一的法线中,每个数字之间有一个空格。
或者我可以这样把它们储存在一个科隆里
22
56
102
9
302
无论哪种方式,我都找不到一种简单的方法来检索这些号码并将它们存放在表格中以供以后使用。 因为问题之一我不知道每个数字有多少位(只能是一位甚至是 5 位)所以我不能使用sscanf
。
那么你们中的任何人都可以帮助我如何将这些数字添加到表格中(无论是单行还是单个冒号中的数字,哪个容易)。 (C语言)
(如果这个问题看起来有点愚蠢,真的很抱歉,但我真的很匆忙)
编辑::文件中的数字数量真的很高
编辑 2:这就是我试图做的(以防数字在一个冒号中)
int i=0,k;
char buffer[500];
fd=fopen("Fdonne.txt", "r"); //fd global variable
fgets(buffer,300, fd);
while(feof(fd) == 0)
{
sscanf(buffer,"%d",tb[i]); //tb already declared also
i++;
fgets(buffer,300, fd);
}
for (k=0; k<(count+1); k++) // count is my X here
printf("%d ",tb[k]);
这似乎是最合乎逻辑的事情,但是,通过 ligne 读取 ligne 并使用 sscanf 但是 smh 当我运行程序时什么也没显示(所以某处有问题)
如果我理解正确,您想获得可以在string.Split
和Linq的帮助下完成的string.Split
:
int[] numbers = File
.ReadLines(@"c:\MyFile.txt")
.SelectMany(line => line.Split(
new char[] { ' ', '\t', '\r', '\n' },
StringSplitOptions.RemoveEmptyEntries))
.Select(item => int.Parse(item))
.ToArray();
如果想将数字存储在文件中:
File
.WriteAllLines(@"c:\SomeOtherFile.txt", numbers);
TextFieldParser datReader = new TextFieldParser(Application.StartupPath + @"write here your file address");
datReader.SetDelimiters(new string[] { " " });
datReader.HasFieldsEnclosedInQuotes = true;
string colFields = datReader.ReadToEnd();
List<string> lineOrder = new List<string>();
using (StringReader sr = new StringReader(colFields))
{
string line;
while ((line = sr.ReadLine()) != null)
{
lineOrder.Add(line);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.