Using type std::string
to accept a sentence, for practice (I haven't worked with strings in C++ much) I'm checking if a character is a vowel or not. I got this:
for(i = 0; i <= analyse.length(); i++) {
if(analyse[i] == 'a' || analyse[i] == 'e' [..etc..]) {
...vowels++;
} else { ...
...consonants++;
}
This works fine if the string is all one word, but the second I add a space (IE: aeio aatest) it will only count the first block and count the space as a consonant, and quit reading the sentence (exiting the for loop or something).
Does a space count as no character == null? Or some oddity with std::string
?, It would be helpful to know why that is happening!
EDIT: I'm simply accepting the string through std::cin, such as:
std::string analyse = "";
std::cin >> analyse;
So we use “%[^\n]s” instead of “%s”. So to get a line of input with space we can go with scanf(“%[^\n]s”,str);
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
Strings in C are represented by arrays of characters. The end of the string is marked with a special character, the null character , which is simply the character with the value 0.
Yes, the character count includes all spaces, punctuation and letters.
I'd guess you're reading your string with something like your_stream >> your_string;
. Operator >>
for strings is defined to work (about) the same as scanf
's %s
conversion, which reads up until it encounters whitespace -- therefore, operator>>
does the same.
You can read an entire line of input instead with std::getline
. You might also want to look at an answer I posted to a previous question (provides some alternatives to std::getline
).
I can't tell from the code that you have pasted, but I'm going to go out on a limb and guess that you're reading into the string using the stream extraction operator (stream >> string).
The stream extraction operator stops when it encounters whitespace.
If this isn't what's going on, can you show us how you're populating your string, and what its contents are?
If I'm right, then you're going to want a different method of reading content into the string. std::getline() is probably the easiest method of reading from a file. It stops at newlines instead of at whitespace.
Edit based on edited question: use this (doublecheck the syntax. I'm not in front of my compiler.):
std::getline(std::cin, analyze);
This ought to stop reading when you press "enter".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With