[英]expected primary-expression before ‘)’ token error on a while loop in a function
我的问题是,在 NumWords function 的 while 循环中,我一直在变量“string”上收到“expected primary-expression before ')' token”错误。该变量在“istringstream inSS(string);”中工作正常。 行,但是当我尝试编译代码时,下一行会产生该错误。 请帮帮我,我很困惑,这让我发疯。
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//函数原型
int NumWords(const string&);
int NumNonWSCharacters(const string&);
void CharReplace(string&, char, char);
char PrintMenu();
//主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);
}
//统计字符串中单词的个数
int NumWords(const string&) {
int count = 0;
istringstream inSS(string);
while (inSS >> string) {
count++;
}
}
//统计字符串中的字符数(不包括空格)
int NumNonWSCharacters(const string&) {
cout << "FINISH\n";
}
//将给定字符串中的一个字符替换为另一个字符
void CharReplace(string&, char, char) {
cout << "FINISH\n";
}
//打印菜单
char PrintMenu() {
cout << "FINISH\n";
}
供你参考。 祝你好运。
我将单词保存在数组单词,字符串向量中。 多个空格或非字符字母都被排除在外。 每个单词由两个整数 n1 和 n2 定义,它们固定单词的开头和结尾。 一个词被定义为一段连续的字符。 这一段是使用 string::substring(n1, n2-n1) 和 push_back 提取到向量中的。
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
typedef std::vector<std::string> WordArray;
int NumWords(const std::string&, WordArray&);
int NumNonWSCharacters(const std::string&);
int main ()
{
std::string text;
WordArray words;
//Input & Output original
std::cout << "Enter a line of text: ";
std::getline(std::cin, text);
std::cout << "\n";
std::cout << "You entered: " << text << "\n";
//How many words
std::cout << "Number of characters = " <<NumNonWSCharacters(text) << std::endl;
int nword = NumWords(text, words);
std::cout << "Number of words = " << nword << std::endl <<std::endl;
for (int i=0; i<words.size(); i++) std::cout <<"word[" << i <<"] = " << words[i] << std::endl;
return 0;
}
int NumNonWSCharacters(const std::string& str)
{
int count = 0;
std::istringstream inSS(str);
char a;
while (inSS >> a)
{
if (a!=' ') count++;
}
return count;
}
#include <cctype>
int NumWords(const std::string& str, WordArray&word)
{
int nword = 0, n1, n2;
char a;
n2 = n1 = 0;
while (n1 < str.size() )
{
if ( std::isalpha(str[n1]) )
{
n2 = n1 + 1;
while ( std::isalpha(str[n2]) ) {n2++;}
word.push_back(str.substr(n1, n2-n1));
n1 = n2+1;
}
else
{
n1++;
while ( !std::isalpha(str[n1]) ){n1++;}
}
}
return word.size();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.