gpt4 book ai didi

c++ - C++字符串流

转载 作者:行者123 更新时间:2023-12-02 09:47:49 26 4
gpt4 key购买 nike

我只是在学习如何在C++中使用流,我有一个问题。
我以为每个流都具有true或false的状态。我想从下面的字符串和1中输入每个单词,直到出现一个单词,但出现错误:

cannot convert 'std::istringstream {aka std::__cxx11::basic_istringstream<char>}' to 'bool' in initialization
bool canReadMore = textIn;


应该是这样的:
antilope  1  ant  1  antagonist  1  antidepressant  1

What am I doing wrong?

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 operator bool is explicit。这意味着您必须自己明确地进行 Actor 表转换:

#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(boolean) 上下文中使用 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

关于c++ - C++字符串流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63853628/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com