Vectors and strings

Okay so I have to write a program that will read in a line of text and output the number of words in the line and the number of occurrences of each letter. And then defines a word to be any string of letters that is delimited at each end by spaces, a period, a comma, or the beginning or end of the line.

My problem is it won't break out of my loop when I enter in a ".", "?", or "!". Can you help figure this out.



#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main ()
{
vector<string> sentence;
int counter(0);
string x;

while (x != "." || x != "?" || x != "!")
{
cin >> x;
sentence.push_back(x);
counter++;
}

cout << counter << endl;
return 0;
}
This is because you are using the or(||) logic operator. OR operates on the principle that only one has to be true. So if you enter in a period then x!="." is false, so far so good. However, a period is not a question mark or exclamation mark so x != "?" || x != "!" are both true and therefore the while condition is true and cannot be stopped.
Oh my gosh, I feel stupid now. Thank you it didn't even think of that.
No problem. Reply back if you need anything and good luck!
okay so my next question is for the numbers of times a letter occurs in the statement. Can I just write a for loop that starts at 65 and ends at 90 for all the letters, or is there another way to run through the string and count ever letter there is?
I'm a bit confused by your question, there are multiple ways to have a count with keys. To get the count of the letters you can for loop through your string and access it like sentence[i]. Some ideas for storing the count of letters would be a count var for each letter a-z, vector of numbers with value as count: 0-25indexes are 1-26 of alphabet; use a std::map.
What I'm asking is how do I run through the string and count ever "a", "b", etc. I just tried

if (sentence[tax] = "B" || sentence[tax] = "b")
{
b++;
}
and it told me that it didn't recognize "operator||", so I took out to see what it would say and it just that I couldn't convert to char (I think).
This: sentence[tax] = "B" || sentence[tax] = "b"
is equivalent to: sentence[tax] = ("B" || (sentence[tax] = "b"))

Perhaps you meant to use the comparison operator (==) rather than the assignment operator (=). Even then you have a problem. "B" is a string literal and sentence[tax] is a single char. Comparing them makes no sense.

if ( sentence[tax] == 'b' || sentence[tax] == 'B' ) would be the correct code for what you were doing here, although it is a rather tedious approach to take to your problem.
yes that did it thank you, I just hope that rest of my code works now.
Topic archived. No new replies allowed.