1. 程式人生 > >//用scanf和printf輸入輸出string//map的應用//Babelfish------三C

//用scanf和printf輸入輸出string//map的應用//Babelfish------三C

You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language. Fortunately, you have a dictionary to help you understand them.
Input
Input consists of up to 100,000 dictionary entries, followed by a blank line, followed by a message of up to 100,000 words. Each dictionary entry is a line containing an English word, followed by a space and a foreign language word. No foreign word appears more than once in the dictionary. The message is a sequence of words in the foreign language, one word on each line. Each word in the input is a sequence of at most 10 lowercase letters.
Output
Output is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as “eh”.
Sample Input
dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay
atcay
ittenkay
oopslay
Sample Output
cat
eh
loops

解題思路:
這道題過程不難,主要就是資料量大需要用scanf和printf輸入輸出,因為有map所以需要用string型別。
一開始不知道怎麼樣scanf和printf輸入輸出string型所以一直有問題。
string型別中有一個.c_str()函式,能返回當前字串的首地址。
printf(“%s”,s.c_str());就可以了
輸入的話需要先用.resize預分配空間,然後再用scanf(“%s”,&s[0]);就可以了。
參考了這兩篇部落格
http://blog.csdn.net/spaceyqy/article/details/24840215
https://www.cnblogs.com/Annetree/p/6501559.html

#include<stdio.h>
#include<string>
#include<map>
using namespace std;

map<string,string> dic;

int main()
{
    string a,b;
    a.resize(15);
    b.resize(15);
    while(1)
    {
        scanf("%s",&a[0]);
        if(dic.count(a)==1)
        {
            break;
        }
        scanf
("%s",&b[0]); dic[b]=a; } if(dic[a]!="")printf("%s\n",dic[a].c_str()); else printf("eh\n"); while(scanf("%s",&a[0])!=EOF) { if(dic[a]!="") printf("%s\n",dic[a].c_str()); else printf("eh\n"); } }