I am currently learning C++ using Addison Wesley's /'programming principles and practice using c++". Here, there is an example that goes:
int main()
{
vector<string> words;
for(string temp; cin>>temp; ) // read whitespace-separated words
words.push_back(temp); // put into vector
cout << "Number of words: " << words.size() << '\n';
sort(words); // sort the words
for (int i = 0; i<words.size(); ++i)
if (i==0 || words[i–1]!=words[i]) // is this a new word?
cout << words[i] << "\n";
}
I understand the code, however, when I am input my words, they don't show up as the output in the command prompt. However, if i switch "string" to "int", then numbers appear just fine. Is there a special case with string vector inputs that I am just not getting?
So from my understanding, cin >> is the input in which i just entered random words. For example "I am learning this language". And afterwards, I typically use the "|" symbol as termination (from what the book has explained). However, there is no output when i press enter. Yet, when i use integers instead of a string, it works as its supposed to, and I use "|" to terminate as well.
Yet, when i use integers instead of a string, it works as its supposed to, and I use "|" to terminate as well.
That's because the "|" is not a valid number so the stream fails. However "|" is a valid string so that will not cause the stream to fail and exit the loop. You will need to enter either Ctrl-D or Ctrl-Z to signal the end of file when you are retrieving the strings.