![](/img/trans.png)
[英]VS2017: How can I write per-file options in .vcxproj, without breaking the filters I've set up?
[英]How can I write float data from a .txt file to a 2-dimensional array w/ VS2017?
如何從.txt文件中讀取浮點數據:
8.9 789.3 845.6
2.45 2.25 2.05
. . .並將每個浮點數寫入數組元素。 我在網上查看過,但找不到有關如何執行此操作的明確答案或教程。 我正在使用VS2017 Enterprise ,並且我的項目資源文件中已經有.txt文件。
這是您可以使用的簡單示例
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *f=fopen("file.txt","r");
float a;
char b[255];
while(!feof(f)){
fscanf(f,"%s",b);
a=atof(b);
printf("%f\n",a);
} fclose(f);
}
我總是從關於如何通過代碼得出答案的解釋中獲得更多,所以這里是我如何思考這個問題(假設對所選語言知之甚少):
首先,我需要通讀一個文件。 我現在上網搜索如何讀取文件。 我找到了幾個讀取文件的示例,並選擇對我最有意義的示例(無論是流式傳輸文件還是將整個文件讀入char *
)。 一旦我弄清楚了,我就可以繼續計算二維數組。
要構建二維數組,我首先需要將二維數組初始化為正確的大小。 如果一個人是真正的初學者,那可能意味着要查找如何初始化 2d 數組。 然后我可以繼續填充數組。
現在,我遍歷二維數組。 如果一個人是真正的初學者,那可能意味着要查找如何迭代 2d 數組。 對於二維數組中的每個單元格,我需要從文件中解析出下一個浮點數並將其插入到單元格中。
這部分取決於您選擇如何讀取文件,可以通過多種方式完成。 假設您正在流式傳輸文件,您需要閱讀下一個“單詞”,然后將該文本轉換為浮點數。 為此,我可能會搜索諸如“在 C 中讀取文本直到空格或換行符”和“將字符串轉換為 C 中的浮點數”之類的內容。
然后剩下要做的就是測試它!
希望有幫助。
使用 system.IO 讀取文件中的文本,然后使用 C# split 轉換為數組。
命名空間
using System;
using System.IO;
using System.Text;
在你的代碼中
string path = @"c:\temp\MyTest.txt";
// Open the file to read from.
string readText = File.ReadAllText(path);
string[] strarray = readText.Split(Convert.ToChar(' '));
如果要將其轉換為double
數組。 使用linq
double[] darray = readText.Split(Convert.ToChar(' ')).Select(n => Convert.ToDouble(n)).ToArray();
將 .txt 文件中的數據浮動到二維數組
找不到有關如何執行此操作的明確答案或教程。
偽代碼大綱
做這些功能
// return 1: success
// return 0: failure
// return -1: EOF or end of line
int read_one_float(FILE *stream, float *f)
fgetc(): read leading white space, if \n encountered, return -1
ungetc(): put non white space character back in stream
if f == NULL, form a dummy location to save data
scanf("%f", f) and return its value
// return > 0: return count of float
// return 0: failure
// return -1: EOF
int read_one_line(FILE *stream, float *f)
count = 0
repeatedly
call read_one_float(f)
if (response != 1) return count
if (f not NULL) f++
count++;
return count
// return > 0: return count of lines
// return 0: failure
// return -1: EOF
int read_FILE(FILE *stream, float **f, int *width)
line = 0;
*width = 0
repeatedly
call read_one_line(f)
if (response <= 0) return line
*width = max (*width, response)
if (f not NULL) f++
line++;
return line
放在一起
int main()
open file
width = 0
line count = read_FILE(file, NULL, &width);
allocate f float[count][width]
REWIND file
read_FILE(file, f, &width);
close file
do something with f
deallocate
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.