0

I'm having some trouble understanding how to use cin.getline and cin.get. I believe I understand the problem, just trying to figure out how to use them in conjunction possibly to solve a problem.

I'm reading from a text file that's read in through cin through command line.

I created a vector of vectors called spaceStation and I want to load it with characters.For example, here's a small portion of the file

M
4
2
//Possible comments
....
#...
E#..
#...

For this, i read in the first three characters properly just using cin>> to load into a variable. Now I need to create a loop to read these multiple characters in on the same line. 1) I'm supposed to ignore all comments 2) I want to run the while loop until a new line is reached that contains no more information

I created a string s so getline(cin,s) should load the entire lines. My question is should i create a cstring s so i can access the individual characters to load or is there a way to use cin.get() to extract the individual characters of the line received by s.

user2817753
  • 1
  • 1
  • 1
  • 2
  • 1
    `std::getline` reads into a `std::string`, and from a `std::string` you can access each character one by one. See e.g. [this reference](http://en.cppreference.com/w/cpp/string/basic_string). – Some programmer dude Sep 26 '13 at 04:21
  • "cppreference" and "cplusplus" sites both provide very handy references, e.g. http://www.cplusplus.com/reference/string and http://www.cplusplus.com/reference/fstream/ifstream/ – kfsone Sep 26 '13 at 06:36
  • did my answer benefit you? – hasan Sep 26 '13 at 09:15

1 Answers1

0
string s;
vector<string> v; // this is the best choice you can iterate like this to get char by char:

for (int i=0;i<v.size();i++)
    for (int j=0;j<v[i].size();j++)
        v[i][j];

// or like this to get strings
for (int i=0;i<v.size();i++)
    v[i];

getline(cin, s); // this is to read the \n (new line) after int in the 3rd line
while (getline(cin,s))// till end of file
{
    if (s.find_first_not_of(".#E") == -1)
    {
        v.push_back(s);
    }
}

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

You also can take advantage of the string class functions.

hasan
  • 23,815
  • 10
  • 63
  • 101