【发布时间】:2020-11-14 10:52:56
【问题描述】:
我正在尝试编写一个函数来计算给定字符串中的单词数,但每次尝试编译代码时都会收到错误消息。
**The error message**: lab4.cpp: In function ‘int NumWords(const string&)’:
lab4.cpp:98:17: error: cannot bind ‘std::basic_istream<char>’ lvalue to ‘std::basic_istream<char>&&’
while (inSS >> str) {
^
In file included from /usr/include/c++/4.8.2/iostream:40:0,
from lab4.cpp:9:
/usr/include/c++/4.8.2/istream:872:5: error: initializing argument 1 of ‘std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&&, _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = const std::basic_string<char>]’
operator>>(basic_istream<_CharT, _Traits>&& __is, _Tp& __x)
^
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//函数原型
int NumWords(const string&);
int NumNonWSCharacters(const string&);
void CharReplace(string&, char, char);
char PrintMenu();
//主函数
int main () {
//Variables
string text;
//Input & Output original
cout << "Enter a line of text: ";
getline(cin, text);
cout << "\n";
cout << "You entered: " << text << "\n";
//How many words
cout << NumWords(text) << "\n";
}
//统计字符串中的单词个数
int NumWords(const string& str) {
int count = 0;
istringstream inSS(str);
while (inSS >> str) {
count++;
}
return count;
}
//统计字符串中的字符个数(不包括空格)
int NumNonWSCharacters(const string&) {
cout << "f";
}
//用给定字符串中的一个字符替换另一个字符
void CharReplace(string&, char, char) {
cout << "FINISH\n";
}
//打印菜单
char PrintMenu() {
cout << "FINISH\n";
}
【问题讨论】:
-
str是 const 限定的,您无法从inSS读取它。 -
提取运算符
>>将写入 到字符串str。但如果str是const,这是不可能的。
标签: c++ function c++11 compiler-errors