【问题标题】:Compiler Error. Expected ';' Before Token [closed]编译器错误。预期的 ';'代币之前[关闭]
【发布时间】:2018-05-17 06:40:55
【问题描述】:
//this application implements use of a simple set
//program does data insertion,searching, and deletion
//program will represent a set of keys
//a user can add a key, delete a key, and check for duplicate keys
#include<iostream>
#include<set>
#include<string>
using namespace std;

int main()
{
string key, answer,answer2;
int i;

std::set<std::string> Keyring;

//prompts user to insert elements in set
for(i = 0; i < 5; i++)
{
cout<<"\nInsert Key " <<i+1<<" Onto Key Ring. Use _ For Spaces"<<endl;
cin >>key;
Keyring.insert(key);

}
//shows resulting key ring
cout<<"\nHere is Completed Key Ring\n"<<endl;
for(std::set<std::string>::iterator it=Keyring.begin(); it !=Keyring.end(); it++) //the '<' operator keeps UNIQUE elements in sorted order
{
std::cout<<" "<<"\n"<< *it; 
}


//Set Deletion and Addition
cout<<"\nWould You Like to Add or Delete From Key Ring?"<<endl;
cout<<"\nType add or delete"<<endl;
cin>>answer;

if(answer=="add")
{
cout<<"\nAdd Another Key. Use _ For Spaces"<<endl;
cin>>key;
Keyring.insert(key);

    if(Keyring.insert(key).second) //checks to see if key already present in set
    {
    cout<<key<<" Successful Addition!"<<endl;
    }   
    else if(!Keyring.insert(key).second)
    {
    cout<<" Duplicate Key Can't Be Added!"<<endl;
    }
}
else(answer=="delete")
{
cout<<"\nDelete A Key. Use _ For Spaces"<<endl;
cin>>key;
Keyring.erase(key);
cout<<"\nNew Keyring"<<endl;
}

for(std::set<std::string>::iterator it=Keyring.begin(); it !=Keyring.end(); it++)
{
std::cout<<" "<<"\n"<< *it;
}
cout<<"\nKeyring size is "<<Keyring.size()<<endl;

//Set Searching
cout<<"\nWant To Search For A Key y/n?"<<endl;
cin>>answer2;

if(answer2=="y")
{
cout<<"\nSearch For A Key. Use _ For Spaces"<<endl;
cout<<"\nWhere Is My..."<<endl;
cin>>key; cout<<" Key?"<<endl;
}
std::set<std::string>::iterator it=Keyring.find(key);

if(it !=Keyring.end())
{
cout<<key<<"\nFound!"<<endl;
}
else
{
cout<<key<<"\nNot Found :("<<endl;
}

return 0;

}

由于此错误,我无法运行我的程序:[Error] 预期为 ';'在'{'标记之前。问题从“设置添加和删除”部分开始。问题在于该部分中的大 If-Else 语句,位于 else 语句开始的行。我已经看了一个小时了,这太令人沮丧了!编译器说应该有一个';'在“else”语句行之前,但从语法上看一切都很好。我检查了嵌套 if 语句的文档,这样我就可以避免这个问题。需要帮助!

【问题讨论】:

  • else(answer=="delete") 看起来很可疑。

标签: c++ if-statement syntax conditional


【解决方案1】:

else(answer=="delete") 应该是else if(answer=="delete"),C++ 没有任何特殊的elif 形式,所以如果你想检查另一个条件,你需要在else 之后开始一个新的if 块。

("delete" == answer)等比较运算符的左侧写上文字也是一个好主意,这样您可以轻松检测意外的赋值错误。

【讨论】:

  • 我通常不使用这样的复杂 if 语句。当它变得复杂时,总是切换语句。只是看不出我如何在这个程序中使用它们。哦,也许下次吧,谢谢。
猜你喜欢
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 2013-09-23
  • 2023-03-31
  • 1970-01-01
  • 2018-06-28
  • 2016-05-01
相关资源
最近更新 更多