将字符串映射到 int CPP - 输出在执行期间挂起

Mapping string to int CPP - Output hangs during execution

我目前正在做黑客等级的练习题。 link 是:https://www.hackerrank.com/challenges/linkedin-practice-dictionaries-and-maps

#include<cstdio>
#include<map>
#include<vector>
#include<conio.h>
#include<iostream>
#include<string>

using namespace std;


map<std::string, int> dict;
map<std::string, int>::iterator k;
int i, j, temp, n;
long long num;
//char check[100][100];
std::string str, sea;
int main()
{
    scanf("%d", &n);
    j = n;

    while(j--)
    {
        scanf("%s %d", &str, &num);
        dict.insert(make_pair(str, num));
    }

    printf("finished\n");
    printf("%s %d\n", "sam", dict["sam"]);
    while(scanf("%s", str))
    {
        if(str.empty())
            break;
        //printf("k is %s\n",str);
        k = dict.find(str);
        if(k != dict.end())
        {
            printf("%s %d\n", str, dict[str]);
        }
        else
        {
            printf("Not found\n");
        }
    }

    getch();
}

程序运行正常,直到 printf 语句 "finished"。然后在 dict 语句的下一个输出中出现

finished
sam 0

并且在while 语句中,当它在map 中搜索字符串时,应用程序挂起并自动关闭。在插入值时我尝试使用:

  1. dict[str] = num;
  2. dict.insert(对(str, num));
  3. dict.insert(make_pair(str, num));

请指出程序中是否需要我进行更正。任何帮助表示赞赏。谢谢!

这条语句,

scanf("%s %d", &str, &num);

… 不是输入 std::string 的有效方式。它具有未定义的行为。所有投注均已取消。

您可以输入到 char 缓冲区,并且方便地 std::string 提供了这样的缓冲区。例如

str.resize( max_item_length );
scanf("%s %d", &str[0], &num);
str.resize( strlen( &str[0] ) );

当然,您可以在整个代码中只使用 C++ iostream,例如

cin >> str >> num;