如何在C++中从文本文件中读取时跳过特定的列
How to skip specific column while reading from text file in C++?
我有一个包含三列的文本文件。我只想读第一篇和第三篇。第二列由名称或日期组成。
输入文件|数据读取
7.1 2000-01-01 3.4 | 7.1 3.4
1.2 2000-01-02 2.5 | 1.2 2.5
或
5.5未知3.9 | 5.5 3.9
1.1未知2.4 | 1.1 2.4
有人能给我一个如何在C++中做到这一点的提示吗?
谢谢!
"有人能给我一个如何在C++中做到这一点的提示吗?">
当然:
- 使用
std::getline
逐行浏览文件,将每一行读取到std::string line;
- 为每行构造一个临时
std::istringstream
对象 - 在此流上使用
>>
运算符填充double
类型的变量(第一列) - 再次使用
>>
将第2列读取到您不会实际使用的std::string
中 - 使用
>>
读取另一个double
(第3列)
例如:
std::ifstream file;
...
std::string line;
while (std::getline(file, line)) {
if (line.empty()) continue; // skips empty lines
std::istringstream is(line); // construct temporary istringstream
double col1, col3;
std::string col2;
if (is >> col1 >> col2 >> col3) {
std::cout << "column 1: " << col1 << " column 3: " << col3 << std::endl;
}
else {
std::cout << "This line didn't meet the expected format." << std::endl;
}
}
有人能给我一个提示如何在C++中做到这一点吗?
只需使用std::basic_istream::operator>>
将跳过的数据放入伪变量,或使用std::basic_istream::ignore()
跳过输入,直到指定下一个字段分隔符。
解决它的最佳方法应该是使用std::ifstream
逐行读取(请参见std::string::getline()
),然后分别解析(并如上所述跳过列)每一行,在输入文件中的所有行上循环使用std::istringstream
。
问题解决如下:
int main()
{
ifstream file("lixo2.txt");
string line; int nl=0; int nc = 0; double temp=0;
vector<vector<double> > matrix;
while (getline(file, line))
{
size_t found = line.find("Unknown");
line.erase (found, 7);
istringstream is(line);
vector<double> myvector;
while(is >> temp)
{
myvector.push_back(temp);
nc = nc+1;
}
matrix.push_back(myvector);
nl =nl+1;
}
return 0;
}
感谢大家!!
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到