First character in a string gets deleted/removed.

Hello everyone, i am very excited to join this community.

I am having a bug that i have not been able to figure out why. I have a function that dynamically adds what the user inputs into a vector to later be used. The problem arrives when the very first word that the user enters has its first character removed (for example "Hello" is stored as "ello"). Every single other word that gets captured this way after the first one does not get this problem. I have tried looking at what the problem is but most threads i find are about getline, which for my purpose won't work. The debugger hasn't really showed me much of anything. Any types would be greatly appreciated.


The function adds an element to the vector. Then it stores the first word of the user input in word_pushed_back. Then this variable gets assigned to the indexed vector as the loop continues. Once the user presses the enter key, the loop ends and returns the completed vector.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
vector<string> get_english_words()
{
	vector<string> english_words;
	
	string word_pushed_back = "";

	for (int i = 0; cin.get() != '\n'; i++)
	{
		english_words.push_back("");
		cin >> word_pushed_back;
		english_words.at(i) = word_pushed_back;
	}
	return english_words;
}
Last edited on
cin.get() extracts and discards the character that was read.

Something like this, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <vector>
#include <string>
#include <sstream> // for std::istringstream

std::vector<std::string> get_words()
{
	std::vector<std::string> all_words;

    // read a full line of input
	std::string line ;
	std::getline( std::cin, line ) ;

	// extract words one by one from the line that was read
	std::istringstream str_stm(line) ; // create a string stream to read from the line
	std::string word ;
	while( str_stm >> word ) all_words.push_back(word) ;

	return all_words ;
}
Ok, so the std::istringstream str_stm(line); does the same thing as if the a user was entering a string on the console correct? I looked at what str does and it streams a string but what does the stm do? or is str_stm simply a variable name of istringstream type?

Then the while( str_stm >> word ) all_words.push_back(word) ; loops while there is a word in the stream to be assigned to word which then gets added to the vector. Is this correct?
> is str_stm simply a variable name of istringstream type?

Yes.


> Then the while( str_stm >> word ) all_words.push_back(word) ; loops while there is
> a word in the stream to be assigned to word which then gets added to the vector. Is this correct?

Yes.
Awesome thanks a lot.
Topic archived. No new replies allowed.