在C语言中从文本文件中读取特定的数据列

Reading in a specific column of data from a text file in C

本文关键字:读取 数据 文件 语言 文本      更新时间:2023-10-16

我的文本文件是这样的:

987 10.50   N   50
383 9.500   N   20
224 12.00   N   40

我只想读取数据的第二列。我怎么会有这种想法?

你不能只读第二列而不读其他内容。

您可以做的是读取所有数据,并忽略除第二列之外的所有内容。例如,读取一行数据(带有std::getline),然后从中提取intdouble,但忽略int和该行的其余部分。

您需要读取所有数据,并丢弃不需要的字段(即:"列")。包含%*d的格式字符串会这样做。

C中,它可能类似于(假设fFILE*句柄)

 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);
 }

p。感谢Jerry Coffin的评论

C89/C90具有strtok函数,可用于逐行读取文件,用"space"分隔符分隔列,然后您可以访问第n个令牌(代表文件中行中的第n列)。

strtok

中声明http://cplusplus.com/reference/cstring/

一些实现也有一个线程安全的可重入版本,称为strtok_r

c++ 中,您可以考虑使用std::istringstream,它需要include: #include <sstream>。比如:

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,它读取列数据到变量