毕竟是没看题解前写的,一直没找出哪里错..
虽然用那种一行逐个变量输入AC了,但这个getline()的写法,我自测了很多都不知道哪里WA了
#include<bits/stdc++.h>
using namespace std;
int N;
string ch;
int main() {
cin >> N;
//当输入N后 回车会产生换行符'\n'
getline(cin, ch);//这里是为了读掉 N 后面的换行符,以防赋值到 s
while (N--) {
string s;
//需要保留空格, 读取一行 对于string用getline(cin, s)
//cin >> s;
getline(cin, s);
int len = s.length();
//简化思路, 分开3个for来处理
//特殊情况, 如果x为0
if (s[0] == '0') {
//只要替换?就好
for (int i = 0; i < len ; i++) {
if (s[i] != '?') cout << s[i];
else cout << 0;
}
cout << endl;
continue;
}
//第1个for 确定数字1
string num1 = "";
for (int i = 0; i < len; i++) {
if (s[i] == ' ') break;
num1 += s[i]; // x不一定都是带0 样例只是没给出其他数字
}
//先反过来看看 后面要转成什么单位
string unit2;
int idx = 0;
for (int i = len-1; i >= 0; i--) {
if (s[i] == ' ') {
//开始截取字符串 从空格的后一个开始
unit2 = s.substr(i+1, len); //参数2可以写很大, 超过的不会记录, 相当于到结尾
//?的位置 在空格的前一个
idx = i - 1;
break; //记得要跳出
}
}
//cout << unit2 << endl;
//第2个for 确定单位1 从num1.length()+1开始
//例如num1 = "6", 空格占1个位置, s[1+1]就是单位1的起始位置
string unit1;
for (int i = num1.length()+1; i < len; i++) {
if (s[i] == ' ') {
unit1 = s.substr(num1.length()+1, i - (num1.length()+1) );
//单位1 第1个字符是否带'k'
/*
* km => m
* km => mm
* kg => g
* kg => mg
*
* m => mm
* g => mg
**/
//cout << unit1 << "转" << unit2 << "check" << endl;
if (unit1 == "km" && unit2 == "mm") cout << s.substr(0, idx) << num1 << "000000 " << unit2 << endl;
if (unit1 == "kg" && unit2 == "mg") cout << s.substr(0, idx) << num1 << "000000 " << unit2 << endl;
if (unit1 == "km" && unit2 == "m") cout << s.substr(0, idx) << num1 << "000 " << unit2 << endl;
if (unit1 == "kg" && unit2 == "g") cout << s.substr(0, idx) << num1 << "000 " << unit2 << endl;
if (unit1 == "m" && unit2 == "mm") cout << s.substr(0, idx) << num1 << "000 " << unit2 << endl;
if (unit1 == "g" && unit2 == "mg") cout << s.substr(0, idx) << num1 << "000 " << unit2 << endl;
break;
}
}
//cout << unit1 << endl;
}
return 0;
}