从C中的文本文件中读取特定的数据列
我的文本文件如下所示:
987 10.50 N 50 383 9.500 N 20 224 12.00 N 40
我想只读第二列数据。 我怎么会这样做?
你不能只是阅读第二列而不阅读其他内容。
您可以做的是读取所有数据,并忽略除第二列之外的所有数据。 例如,读取一行数据(使用std::getline
)然后从中提取一个int
和一个double
,但忽略int
和行的其余部分。
您需要读取所有数据,并丢弃不需要的字段(即“列”)。 包含%*d
格式字符串正在执行此操作。
在C中 ,它可能是这样的(假设f
是FILE*
句柄)
while (!feof(f)) { int n=0; double x=0.0; char c[4]; int p=0; if (fscanf(f, " %*d %f %*[AZ] %*d", &x) < 1) break; do_something(x); }
PS。 感谢Jerry Coffin的评论
C89 / C90具有可用于逐行读取文件的函数strtok
,使用“space”分隔符分隔列,然后您可以访问第n个标记(表示文件中该行的第n列)。
strtok
宣布成立
http://cplusplus.com/reference/cstring/
某些实现还具有名为strtok_r
的线程安全可重入版本。
在C ++中,你可以考虑使用std::istringstream
,它需要include: #include
。 就像是:
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 }
std::istringstream
作用是允许您将std::string
视为输入流,就像常规文件一样。
您可以使用iss >> column1 >> column2
将列数据读入vaiables。