如何从txt读取数据到数组 [英] how to read data from txt to an array
本文介绍了如何从txt读取数据到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是datafile.txt中的数据,
线:30,
num0 = 1
num1 = 3
num2 = 2
...
num29 = 5
我想将num0的值导入到num29到array [29],我要怎么实现,谢谢!!
this is the data in datafile.txt,
line:30,
num0=1
num1=3
num2=2
...
num29=5
I want to import the value of num0 to num29 to array[29],how can I realize this,thank you !
推荐答案
您可以使用sscanf进行如下操作.但是您应该知道每一行的格式.在这里,我们假设行要么被格式化为
"line:30""
或
num0 = 1
所以我们将代码编写如下
You can do this using sscanf as below. But you should know the format of each line. here we assume that lines either get formatted like
"line:30,"
or
num0=1
so we write our code as below
CString csLine; // csLine has each line text
int c, d;
if( !sscanf( csLine, "num%d=%d", &c, &d ) // c will have 0 and d will have 1 incase of num0=1
{
if( !sscabf( csLine, "line:%d", &c ) // c will have 30 incase of "line:30"
{
// Some incorrect/unexpected format for the line
}
}
希望您有主意
hope you got the idea
首先,您需要了解如何读取文件.请参阅:
C ++样式: http://www.cplusplus.com/doc/tutorial/files/ [ ^ ];
C样式: http://www.cplusplus.com/forum/beginner/32690/ [ ^ ].
您还可以使用Resmi Anna演示的sscanf
:
http://www.cplusplus.com/reference/clibrary/cstdio/scanf/ [ ^ ].
—SA
First, you need to know how to read files. Please see:
C++ style: http://www.cplusplus.com/doc/tutorial/files/[^];
C style: http://www.cplusplus.com/forum/beginner/32690/[^].
You can also use thesscanf
as demonstrated by Resmi Anna:
http://www.cplusplus.com/reference/clibrary/cstdio/scanf/[^].
—SA
这篇关于如何从txt读取数据到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文