首页 > 解决方案 > 错误:字符串之前的预期主表达式

问题描述

我想读取一个文件并将单词出现在 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){
                                   ^

标签: c++

解决方案


std::string s不是一个有效的表达式,它是一个语句。改为在循环外声明字符串:

std::string s;
while(declaration >> s){
    M[s]=0;
}

推荐阅读