【问题标题】:I do not understand this c++ error but I need help fixing it我不明白这个 c++ 错误,但我需要帮助来修复它
【发布时间】: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 读取它。
  • 提取运算符&gt;&gt;写入 到字符串str。但如果strconst,这是不可能的。

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


【解决方案1】:

您的 NumWords 函数有问题

int NumWords(const string& str) {

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

    count++;

}
return count;

}

您正在尝试使用 const 参数 str 作为接收 inSS &gt;&gt; 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 函数缺少返回值。这应该很容易解决。

【讨论】:

    猜你喜欢
    • 2020-08-06
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多