Replicating cin String function

Hello. I'm creating a class that replicates some functions of the string class and I'm having trouble coming up with a function that should behave like "cin << str" where str is an object of the string class. So the function should obtain a mystring from user input. This function should only get the characters of the mystring and not any spaces or '\n'.

So for example in the main:
1
2
3
mystring word;
cout << "Input a mystring: ";
word.get();


If I type in "hi there", only "hi" should be obtained. The get function should perform in this manner. Here is what I have so far.

mystring.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ifndef MYSTRING_H
#define MYSTRING_H

#include <vector>

using namespace std;

class mystring
{
	private:

		vector<char> str; //vector of characters.

	public:

		mystring(); // default constructor.
		void get(void); // function that replicates cin.
};

#endif 


mystring.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "mystring.h"

#include <iostream>
#include <vector>

using namespace std;

// Constructor that initializes mystring of zero length.
mystring::mystring()
{
}

// Mimic behavior of cin << str.
void mystring::get(void)
{
	for (int i = 0; i < (int) str.size(); i++)
		{
			//str.push_back();
			char c; // c represents a character of mystring.
			c = str[i];
			cin.get(c);
		}
}


I realize what I have so far is incorrect because the push back will just keep on extending the size of the string, so I will never exit the for loop. How will I be able to obtain each character of an inputted mystring while also increasing the vector by one for each character? Also, how would I deal with the function only taking in characters that do not include spaces or '\n'? Thanks and I appreciate it.
This is the snippet I'm working on:

1
2
3
4
5
6
7
8
9
10
void mystring::get(void)
{
	for (int i = 0; i < (int) str.size(); i++)
		{
			//str.push_back();
			char c; // c represents a character of mystring.
			c = str[i];
			cin.get(c);
		}
}


To clarify, I need the function to take in each character of a string, which my function calls "mystring." I also need for the vector to increase its size by one for each additional character read in, so that the str vector could then have any slots to hold in each character. But my issues is that each time I use push_back, then the str.size() will also increase and be greater than i, so I"ll never exit the for loop. How would I rearrange the code in order for it to do what I want, without continuously staying in the loop?
Topic archived. No new replies allowed.