C ++:为什么空格在读取时总是以字符串结尾? [英] C++: Why does space always terminate a string when read?
问题描述
使用类型 std :: string
接受一个句子,以进行练习(我在C ++中使用字符串的方式不多),我正在检查字符是否为元音.我知道了:
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++;
}
如果字符串全是一个单词,这很好用,但是第二个字符串我加了一个空格(即: aeio aatest ),它只会将第一个块算作一个辅音,并且退出阅读句子(退出for循环之类的东西).
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).
空格是否视为无字符==空?还是与 std :: string
?有点奇怪,知道为什么会这样会很有帮助!
Does a space count as no character == null? Or some oddity with std::string
?, It would be helpful to know why that is happening!
我只是通过std :: cin接受字符串,例如:
I'm simply accepting the string through std::cin, such as:
std::string analyse = "";
std::cin >> analyse;
推荐答案
我猜您正在使用类似 your_stream>>的字符串读取字符串.your_string;
.字符串的运算符>>
定义为(大约)与 scanf
的%s
转换相同,直到读取该转换为止.遇到空格-因此, operator>>
也是一样.
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.
您可以使用 std :: getline
读取整行输入.您可能还需要查看
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
).
这篇关于C ++:为什么空格在读取时总是以字符串结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!