Reputation: 15
This is a noob approach to vectors. The following program is really simple, yet i don't understand what i do wrong. It is small so i trust that reading it won't be a trouble. It is supposed to create a vector and add strings to it. Then print the strings on the screen. If the string has been printed, it skips it and goes to the next one. Also, if the string is one of the disliked words (in this case only the word "left"), then it also skips it.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string>words;
string temp,disliked;
disliked = "left";
while(cin>>temp)
{
words.push_back(temp);
}
for(int i=0; i<words.size(); i++)
{
if(( i==0 || words[i] != disliked && words[i-1]!=words[i]))
{
cout << words[i] << endl;
}
}
return 0;
}
This program is from Stroustrup's book "Programming, principles and practice using c++". I used the code i found in the book and yet when i run the code, the while loop never seems to end. What could be wrong with cin>>temp; ? Edit: When i run the program, the while loop never seems to stop. I have tried "failling" to put a string as input so that the cin>>temp; would also fail. But no matter the type of data i enter as input, the cin never seems to fail. In stroustrup's book the code is exactly like that, which is weird because i encounter logical errors that i cannot pinpoint. The program was supposed to stop when i enter something other that a string. Then the while loop condition would fail, the loop would end and the for loop would begin, leaving me with a nice vector and a few strings. Thank you for your time.
Upvotes: 0
Views: 65
Reputation: 206667
Use of
if((words[i] != disliked && words[i-1]!=words[i]) || i==0)
is a problem since i == 0
is the second clause of the ||
. words[-1]
will be accessed before you check that, which causes undefined behavior.
Change it to:
if( (words[i] != disliked) && (i == 0 || words[i-1] != words[i]))
To make your code more readable, use {}
to make the scopes of the blocks a bit clearer.
int main()
{
vector<string>words;
string temp,disliked;
disliked = "left";
cout << "bam" << endl;
while(cin>>temp)
{
words.push_back(temp);
}
cout << "bam" << endl;
for(int i=0; i<words.size(); i++)
{
if ( (words[i] != disliked) && (i == 0 || words[i-1] != words[i]) )
{
cout << words[i] << endl;
}
}
return 0;
}
Upvotes: 0