2

everybody I've been running into this problem with my homework for awhile. I tried to get help but was answered with "I can't help". The assignment is to parse a file and calculate the given shapes perimeter or area. Here is what I have so far:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;

vector<string> parseString(string); // prototype

int main()
{
  ifstream fin;
  string str;

  fin.open("Shapes.input.txt");

  while(!fin.eof())
  {
    std::getline(fin,str);
    vector<string> tokens = parseString(str);
    cout << tokens[0];
  }
  fin.close();
}


vector<string> parseString(string str)
{
  stringstream s(str);
  istream_iterator<string> begin(s), end;
  return vector<string>(begin, end);
}

The code will successfully build but I get an error for: EXC_BAD_ACCESS. I am not sure how to debug this. I will include the data I made in the file as well to test this portion.

SQUARE 5 SQUARE 7

Sorry if this is a lengthy post, it is my first time posting and I would appreciate any help.

Amit
  • 21
  • 3
  • Your loop is wrong. the last `getline` will fail. Read this: [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). Related, your code assumes a vector with at least one token, an assertion you should probably check before blindly assuming it via `operator[]` on that vector. – WhozCraig Feb 14 '17 at 07:05
  • Welcome to Stack Overflow! The post is of reasonable length. Congratulations on actually posting a [mcve], including the input data - that's a lot more than most people manage. I suggest reading [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) by Eric Lippert. – Martin Bonner supports Monica Feb 14 '17 at 07:06
  • Incidentally, this is an excellent example of why `using namespace std` is a bad idea. It's not obvious (to a reader) when you write `vector(begin, end);` whether you mean the local variables `begin`, `end`, or the library functions `std::begin`, `std::end`. That makes it harder to read your code. – Martin Bonner supports Monica Feb 14 '17 at 07:08
  • thank you everyone, I changed my code but my code still does not read the file, it may have something to do with @WhozCraig 's comment. This is what the code contains right now: ifstream fin; string str; fin.open("Shapes.input.txt"); if (fin.is_open()) { while(fin >> str) { fin >> str; vector tokens = parseString(str); //test output for (int i = 0; i < 10; i++) cout << tokens[i]; } } – Amit Feb 24 '17 at 00:53

0 Answers0