我编写了一个递归函数,可以反转单词的顺序,但是当该函数以句子作为输入时,不会给出输出。以下是我的代码:
void reverseWord(void){
string word;
if(!(cin>>word)){
return;
}
reverseWord();
cout<<word<<" ";
}
但是在《C++ Primer(第五版)》中,有这样一个读取未知数量字符串的示例代码:
int main(){
string word;
while(cin>>word)
cout<<word<<endl;
return 0;
}
问题来自于表达式“!(cin<
为什么表达式 !(cin>>word) 会导致无限递归?
你的代码没有任何问题!问题是在输入流上生成 eof(文件结束符)。
std::stringstream
演示这一点的一种方法是添加
std::istream&
作为参数,并使用 stringstream
。当字符串流用完字符时,它将失败。
std::string s{ "This is a test." };
std::stringstream sst{ s };
if (!(sst >> word)) // this fails after reading the word "test."
{
// ...
}
这是完整的程序。
// main.cpp
#include <iostream>
#include <sstream>
#include <string>
void reverseWord(std::istream& ist) {
std::string word;
if (!(ist >> word)) {
return;
}
reverseWord(ist);
std::cout << word << " ";
}
int main()
{
std::string s{ "This is a test." };
std::stringstream sst{ s };
reverseWord(sst);
}
// end file: main.cpp