在C语言中从文本文件中读取特定的数据列
Reading in a specific column of data from a text file in 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 %*[A-Z] %*d", &x) < 1)
break;
do_something(x);
}
p。感谢Jerry Coffin的评论
C89/C90具有strtok
函数,可用于逐行读取文件,用"space"分隔符分隔列,然后您可以访问第n个令牌(代表文件中行中的第n列)。
strtok
在
一些实现也有一个线程安全的可重入版本,称为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
,它读取列数据到变量
相关文章:
- 如何在ros2中从rosbag2读取数据
- OpenCV 和从 OutputArrays 或 (Mat) 读取数据
- 使用C++从磁卡读卡器MT188读取数据
- HDF5 简单读取数据集失败
- 嵌套结构,从由空行分隔的文件中读取数据
- 不要从输入队列套接字读取数据
- 从文件中读取数据,操作员>>
- 如何从excel文件中读取数据并存储到变量中?
- C++:从文件中读取x y数据会产生无限循环吗
- 无法通过FT232RL读取数据
- 如何从QNetworkReply读取数据?
- C++ 逐行从文件(包含空格)读取数据
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 我们可以从 TXT 文件中读取数据并使用 C 和 C++ 将其保存到 SQL 数据库吗?
- 从多个 tcp 连接读取数据
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- Qt TCP服务器不从客户端读取数据
- 累积从 C++11 中的文件中读取数据的整数
- 从 txt 文件中读取数据的最简单方法
- 从 txt 文件中读取数据的 Getline