[英]Reading in a specific column of data from a text file in C
My text file looks like this: 我的文本文件如下所示:
987 10.50 N 50
383 9.500 N 20
224 12.00 N 40
I want to read only the second column of data. 我想只读第二列数据。 How would I got about doing this?
我怎么会这样做?
You can't just read the second column without reading anything else. 你不能在没有阅读任何其他内容的情况下阅读第二列。
What you can do is read all the data, and ignore everything but the second column. 你可以做的是读取所有数据,并忽略除第二列之外的所有数据。 For example, read a line of data (with
std::getline
) then from it extract an int
and a double
, but ignore both the int
and the rest of the line. 例如,读取一行数据(使用
std::getline
)然后从中提取一个int
和一个double
,但忽略int
和行的其余部分。
You'll need to read all the data, and discard the unneeded fields (ie "columns"). 您需要读取所有数据,并丢弃不需要的字段(即“列”)。 Format strings containing
%*d
are doing that. 包含
%*d
格式字符串正在执行此操作。
In C , it could be something like (assuming f
is a FILE*
handle) 在C中 ,它可能是这样的(假设
f
是一个FILE*
句柄)
while (!feof(f)) {
int n=0; double x=0.0; char c[4]; int p=0;
if (fscanf(f, " %*d %f %*[A-Z] %*d", &x) < 1)
break;
do_something(x);
}
PS. PS。 Thanks to Jerry Coffin for his comment
感谢Jerry Coffin的评论
C89/C90 has the function strtok
that could be used to read the file line by line, separate the columns with the "space" delimiter and then you could access the nth token (representing the nth column in that row in the file). C89 / C90具有函数
strtok
,可用于逐行读取文件,使用“space”分隔符分隔列,然后您可以访问第n个标记(表示文件中该行的第n列)。
strtok
is declared in strtok
在宣布
http://cplusplus.com/reference/cstring/ http://cplusplus.com/reference/cstring/
Some implementations also have a thread-safe re-entrant version called strtok_r
. 某些实现还具有名为
strtok_r
的线程安全可重入版本。
In C++ you could consider using std::istringstream
, which requires the include: #include <sstream>
. 在C ++中,你可以考虑使用
std::istringstream
,它需要include: #include <sstream>
。 Something like: 就像是:
std::ifstream ifs("mydatafile.txt");
std::string line;
while(std::getline(ifs, line)) // read one line from ifs
{
std::istringstream iss(line); // access line as a stream
// we only need the first two columns
int column1;
float column2;
iss >> column1 >> column2; // no need to read further
// do what you will with column2
}
What std::istringstream
does is allow you to treat a std::string
like an input stream just like a regular file. std::istringstream
作用是允许您将std::string
视为输入流,就像常规文件一样。
The you can use iss >> column1 >> column2
which reads the column data into the vaiables. 您可以使用
iss >> column1 >> column2
将列数据读入vaiables。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.