[英]C++ String Stream
我只是在學習如何在 C++ 中使用流,我有一個問題。
我認為每個流都有真或假的狀態。 我想輸入下面字符串中的每個單詞和 1 直到有一個單詞,但出現錯誤:
無法在初始化時將“std::istringstream {aka std::__cxx11::basic_istringstream<char>}”轉換為“bool”
bool canReadMore = textIn;
它應該是這樣的:
antilope 1 ant 1 antagonist 1 antidepressant 1
我究竟做錯了什么?
int main() {
std:: string text = "antilope ant antagonist antidepressant";
std:: istringstream textIn(text);
for(int i = 0; i < 5; i++ ){
std:: string s;
textIn >> s;
bool canReadMore = textIn;
std::cout << s << std:: endl;
std::cout << canReadMore << std:: endl;
}
return 0;
}
``1
從 C++11 開始, std::istringstream
運算符bool
是顯式的。 這意味着您必須自己明確地進行演員表:
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string text = "antilope ant antagonist antidepressant";
std::istringstream textIn(text);
for (int i = 0; i < 5; i++) {
std::string s;
textIn >> s;
bool canReadMore = bool(textIn);
std::cout << s << std::endl;
std::cout << canReadMore << std::endl;
}
return 0;
}
輸出:
./a.out
antilope
1
ant
1
antagonist
1
antidepressant
1
0
現在,如果您在 bool 上下文中使用std::stringstream
,則轉換將是自動的。 這是一個慣用的用法:
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string text = "antilope ant antagonist antidepressant";
std::istringstream textIn(text);
std::string s;
while (textIn >> s) {
std::cout << s << "\n";
}
}
輸出:
antilope
ant
antagonist
antidepressant
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.