将包含括号中字符的文件读入整数向量

时间:2014-11-29 01:49:57

标签: c++11 vector integer text-files ifstream

我试图将包含在括号中的字符的文件读入整数向量。

我的文字档案:

(2 3 4 9 10 14 15 16 17 19)

继承我的代码:

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;


int main(){
  ifstream file;
  file.open("moves.txt");

  vector<int> V;
  char c;

  if (file){
    while (file.get(c)){
      if (c != '(' && c != ')' && c != ' ')
        V.push_back(c - '0');
    }
  }
  else{
    cout << "Error openning file." << endl;
  }

  for (int i = 0; i < V.size(); i++)
    cout << V[i] << endl;
}

我的输出:

2
3
4
9
1
0
1
4
1
5
1
6
1
7
1
9
-38

期望的输出:

2 
3 
4 
9 
10 
14 
15 
16 
17 
19

导致两位数字分离的原因是什么,为什么输出结尾有一个负数?

1 个答案:

答案 0 :(得分:2)

不要逐个读取字符:读一行,并解析其中的数字。

使用this answeris_number(c ++ 11)函数:

bool is_number(const std::string& s)
{
    return !s.empty() && std::find_if(s.begin(),
        s.end(), [](char c) { return !std::isdigit(c); }) == s.end();
}

您可以使用std::getline逐行阅读,然后将数字流式传输到std::stringstreamstd::stoi可用于将字符串转换为整数:

 std::string line;
 while(std::getline(file, line))
 {
    line.replace(line.begin(), line.begin() + 1, "");
    line.replace(line.end() - 2, line.end() - 1, "");
    std::string numberStr;
    std::stringstream ss(line);
    while (ss >> numberStr){
      if (is_number(numberStr))
        v.push_back(std::stoi(numberStr));
    }
 }

您必须使替换更加强大(通过检查这些位置是否存在括号)