I am trying to write a function that counts the number of words in a given string but I keep getting an error message every time I try to compile the code.
**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;
//Function prototypes
int NumWords(const string&);
int NumNonWSCharacters(const string&);
void CharReplace(string&, char, char);
char PrintMenu();
//Main function
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";
}
//Counts the number of words in a string
int NumWords(const string& str) {
int count = 0;
istringstream inSS(str);
while (inSS >> str) {
count++;
}
return count;
}
//Count the number of characters (not including whitespace) in a string
int NumNonWSCharacters(const string&) {
cout << "f";
}
//Replaces one character with another in a given string
void CharReplace(string&, char, char) {
cout << "FINISH\n";
}
//Prints the menu
char PrintMenu() {
cout << "FINISH\n";
}
Aucun commentaire:
Enregistrer un commentaire