2014-01-28 72 views
0

我有一个三列的文本文件。我只想读第一和第三。第二列由名称或日期组成。如何从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++中做到这一点?

谢谢!

+0

LihO,谢谢你的帮助。 但是,当我有一个文件与几列我如何阅读他们。但总是跳第二列。 –

回答

0

有人可以给我一个提示如何在C++中做到这一点?

只需使用std::basic_istream::operator>>把跳过数据到一个虚拟变量,或使用std::basic_istream::ignore()跳过输入,直到指定下一个字段分隔符。

解决应当读出由线线的最佳方式使用std::ifstream(参见std::string::getline()),然后解析(并跳过列如上所述)分开的每一行,在循环中使用std::istringstream超过在输入文件中的所有行。

1

“有人能给我一个提示如何在C++中做到这一点?”

没问题:

  1. 经过使用std::getline行文件行,读每一行成std::string line;
  2. 构建一个临时std::istringstream对象每一行
  3. 使用>>运营商在此流填写double类型的变量(第1列)
  4. 再次使用>>将第2列读入std::string,你不会真正使用
  5. 使用>>阅读另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; 
    } 
} 
0

问题解决如下:

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

谢谢大家!

相关问题