簡體   English   中英

如何從文件中讀取數字

[英]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.SplitLinq的幫助下完成的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM