将字符串映射到整型CPP -输出在执行期间挂起
Mapping string to int CPP - Output hangs during execution
我目前正在做一个黑客等级的练习问题。链接: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;
- dict类型。插入(一对(str, num));
- 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;
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- 如何根据单词在文本中出现的概率输出单词