Search code examples
c++11vectorintegertext-filesifstream

Reading a file containing characters in parentheses into a vector of integers


I am attempting to read in a file containing characters enclosed in parentheses into a vector of integers.

My text file:

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

Heres my code:

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

My Output:

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

Desired output:

2 
3 
4 
9 
10 
14 
15 
16 
17 
19

What is causing the separation of two digit numbers and why is there a negative number at the end of my output?


Solution

  • Don't read characters one by one : read a line, and parse the numbers within it.

    By using the is_number (c++11) function of this answer :

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

    You can read line by line with std::getline and then stream the numbers to a std::stringstream. std::stoi can be used to convert a string to an integer :

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

    You'd have to make the replace more robust (by checking the presence of parentheses at these positions)