c++ - 错误:字符串之前的预期主表达式
问题描述
我想读取一个文件并将单词出现在 std::map 中的次数。所以我做了以下代码:
#include <fstream>
#include <string>
#include <map>
int main() {
std::map<std::string, unsigned> M;
std::ifstream declaration("declaration.txt");
while(declaration >> std::string s){
M[s]=0;
}
while(declaration >> std::string s){
M[s]=M[s]+1;
}
declaration.close();
return 0;
}
我收到以下错误消息:
text_analyse.cpp: In function ‘int main()’:
text_analyse.cpp:8:35: error: expected primary-expression before ‘s’
while(declaration >> std::string s){
^
text_analyse.cpp:8:34: error: expected ‘)’ before ‘s’
while(declaration >> std::string s){
~ ^~
)
text_analyse.cpp:8:35: error: ‘s’ was not declared in this scope
while(declaration >> std::string s){
^
text_analyse.cpp:11:35: error: expected primary-expression before ‘s’
while(declaration >> std::string s){
^
text_analyse.cpp:11:34: error: expected ‘)’ before ‘s’
while(declaration >> std::string s){
~ ^~
)
text_analyse.cpp:11:35: error: ‘s’ was not declared in this scope
while(declaration >> std::string s){
^
解决方案
std::string s
不是一个有效的表达式,它是一个语句。改为在循环外声明字符串:
std::string s;
while(declaration >> s){
M[s]=0;
}
推荐阅读
- javascript - 由于一些错误,React-Native Flatlist 没有 Rendring
- python - 多个文本字段拒绝加载所选对象
- python - 在 NodeMCU 中使用 Micropython 访问多个传感器值?
- c# - 如何将游戏对象数组的值从一个脚本获取到另一个脚本?
- javascript - ngFor 在对象而不是数组上?
- c# - Asp.Net C#中Laravel的dd函数等价
- docker - 如何在 docker 中使用 gunicorn 运行烧瓶应用程序(导入本地模块)
- opendaylight - 无法在 Opendaylight Web 界面中查看交换机和主机
- angular - 授权标头未在 Angular 6 中发送
- c - 如何从编译的elf文件中提取所有函数,即使函数没有符号