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

Mapping string to int CPP - Output hangs during execution

本文关键字:输出 执行期 挂起 CPP 字符串 映射 整型      更新时间:2023-10-16

我目前正在做一个黑客等级的练习问题。链接: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("finishedn");
    printf("%s %dn", "sam", dict["sam"]);
    while(scanf("%s", str))
    {
        if(str.empty())
            break;
        //printf("k is %sn",str);
        k = dict.find(str);
        if(k != dict.end())
        {
            printf("%s %dn", str, dict[str]);
        }
        else
        {
            printf("Not foundn");
        }
    }
    getch();
}

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

finished
sam 0

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

    dict[str] = num;
  1. dict类型。插入(一对(str, num));
  2. dict类型。插入(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++的iostreams,例如

cin >> str >> num;