码迷,mamicode.com
首页 > 其他好文 > 详细

题目1029:魔咒词典(map使用以及字符串读取函数总结)

时间:2017-04-30 16:06:16      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:https   printf   class   pen   位置   代码   isp   定义   总结   

 

题目链接:http://ac.jobdu.com/problem.php?pid=1029

详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus

 

技术分享
//
//  1029 魔咒词典.cpp
//  Jobdu
//
//  Created by PengFei_Zheng on 30/04/2017.
//  Copyright © 2017 PengFei_Zheng. All rights reserved.
//
 
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <cstring>
#include <cmath>
#include <map>
#define MAX_SIZE 110
//#define debug
using namespace std;
 
map<string,string> myMap;
 
char s[MAX_SIZE];
string str;
string curse;
string fun;
int n;
 
int main(){
#ifdef debug
    freopen("/Users/pengfei_zheng/Desktop/input.txt", "r", stdin);
#endif
    while(gets(s)){
        str = s;
        if(str=="@END@") break;
        int len = (int)str.size();
        int i;
        for(i = 0 ; i < len ; i ++){
            if(str[i]==])
                break;
        }
        curse = str.substr(0,i+1);
        fun = str.substr(i+2,len);
        myMap[curse]=fun;
        myMap[fun]=curse;
    }
    scanf("%d\n",&n);
    while(n--){
        gets(s);
        str = s;
        if(myMap.count(s)==0){
            printf("what?\n");
        }
        else{
            string tmp = myMap[str];
            if(tmp[0]==[){
                tmp = tmp.substr(1,tmp.length()-2);
            }
            printf("%s\n",tmp.c_str());
        }
    }
    return 0;
}
/**************************************************************
    Problem: 1029
    User: zpfbuaa
    Language: C++
    Result: Accepted
    Time:20 ms
    Memory:2716 kb
****************************************************************/
参考代码

一、gets函数  

  C语言中提供的gets函数存在一些安全隐患。gets函数定义如下:

char * gets ( char * str );

  gets() 函数的形参只有一个指针。它会从标准输入流中读字符到一块连续的内存地址空间中。这块地址空间的开始位置就是指针 str 指向的位置。当在输入流中遇到文件结束符( EOF )或者换行符(\n)时,读取操作结束。

  当读入换行符(\n)时,该字符不会被放入那块连续的地址空间中。在读取结束时, gets() 会自动在内存空间的末尾追加一个 NULL 字符。

  经过上述这些操作,这个函数得到的就是从标准输入进来的,以 NULL 字符结尾的C字符串。如果读入的字符流是一整行的话,行尾的换行符将会被舍去。

gets函数使用举例:

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <cstring>
#include <algorithm>
#include <cmath>
#define MAX_SIZE 10

using namespace std;

char str[MAX_SIZE];

int main(){
    while(gets(str)){
        printf("str = %s\n",str);
    }
}

运行截图:

技术分享

二、fgets函数  

函数的原型如下:

题目1029:魔咒词典(map使用以及字符串读取函数总结)

标签:https   printf   class   pen   位置   代码   isp   定义   总结   

原文地址:http://www.cnblogs.com/zpfbuaa/p/6789499.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!