我非常新编码,并且在codeforces.com上一直在练习一些简单的问题。我正在研究this problem,但它似乎要求输入(一次全部)产生输出(一次全部)。我只能弄清楚如何一次获得一个输出。
以下是该问题的基本说明:
输入
第一行包含整数n(1≤n≤100)。以下n行中的每一行包含一个单词。所有单词都由小写拉丁字母组成,长度为1到100个字符。
输出
打印n行。第i行应包含从输入数据中替换第i个字的结果。
实施例
输入
4
字
定位
国际化
火山肺矽病
输出
字
L10N
I18N
P43S
这是我的代码:
#include <iostream>
#include <string>
using namespace std;
void wordToNumbers(string word){
int midLetters = word.length();
char firstLetter = word.front();
char lastLetter = word.back();
cout <<firstLetter <<(midLetters-2) <<lastLetter <<endl;
}
int main(){
string wordInput;
string firstNum;
getline(cin,firstNum);
int i = stoi(firstNum);
for(i>=1; i--;){
getline(cin,wordInput);
if (wordInput.length() > 10){
wordToNumbers(wordInput);
} else {
cout <<wordInput <<endl;
}
}
return 0;
}
答案 0 :(得分:0)
我也是c ++的初学者。我的想法是先将所有行保存在缓冲区中,然后将所有内容写入std :: cout。
我使用std :: vector作为缓冲区,导致IMO很容易理解,在很多情况下非常有用。基本上它是一个更好的阵列。您可以阅读有关std :: vector here的更多信息。
#include <iostream>
#include <string>
//for use of std::vector container
#include <vector>
using namespace std;
void wordToNumbers(string word){
int midLetters = word.length();
char firstLetter = word.front();
char lastLetter = word.back();
cout <<firstLetter <<(midLetters-2) <<lastLetter <<endl;
}
int main(){
string wordInput;
string firstNum;
//container for buffering all our strings
vector<string> bufferStrings;
getline(cin,firstNum);
int i = stoi(firstNum);
//read line by line and save every line in our buffer-container
for(i>=1; i--;){
getline(cin,wordInput);
//append the new string to our buffer
bufferStrings.push_back(wordInput);
}
//now iterate through the buffer and write everything to cout
for(int index = 0; index < bufferStrings.size(); ++index) {
if (bufferStrings[index].length() > 10){
wordToNumbers(bufferStrings[index]);
} else {
cout <<bufferStrings[index] <<endl;
}
}
return 0;
}
可能这不是最好或最美的解决方案,但应该很容易理解:)
答案 1 :(得分:0)
完全可以逐行读取和打印行的输出。
完全接受您的解决方案:http://codeforces.com/contest/71/submission/16659519