c++ - 我不明白这个 c++ 错误,但我需要帮助来修复它

标签 c++ function c++11 compiler-errors

我正在尝试编写一个函数来计算给定字符串中的单词数,但每次尝试编译代码时都会收到错误消息。

**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;
//函数原型(prototype)
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";

}

最佳答案

您的 NumWords 函数有问题

int NumWords(const string& str) {

int count = 0;
istringstream inSS(str);
while (inSS >> str) {    // RIGHT HERE

    count++;

}
return count;

}
您正在尝试使用 const 参数 str ,作为接收inSS >> str的流输出的变量.既然是const,那inSS 是不可能的可以写进去。这就是编译器所提示的。只需使用一个临时变量来解决这个问题。
int NumWords(const string& str) {

    int count = 0;
    istringstream inSS(str);
    std::string tmp;         // dummy string

    while (inSS >> tmp) {    // string into tmp
        count++;
    }
    return count;
}
另外,您的 NumNonWSCharactersPrintMenu函数缺少返回值。这应该很容易解决。

关于c++ - 我不明白这个 c++ 错误,但我需要帮助来修复它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64833111/

相关文章:

Python:使用 1 个用户名但不同的密码登录

Javascript/Jquery 通过事件切换对象

c++ - 嵌套的基于范围的 for 语句是否严格合法?

c++ - fabsf 是 C++11 中 std 命名空间的一部分吗?

c++ - 为什么这段代码会在提到的地方崩溃?

c++ - 当父类(super class)持有指向 X 的指针,子类持有 Y : X

c++ - openssl 和 linux bash 计算之间的 MD5 不匹配

function - 用于在另一个函数内部定义辅助函数的 OCaml 语法?

c++ - 使用模板参数包代替宏

c++ - 为什么数组被认为比 STL 容器更好?