为什么在输入的第一行输入测试用例数量后得到垃圾值?

Why I am getting a garbage value after entering number of test cases in the first line of the input?

本文关键字:输入 一行 为什么 测试用例      更新时间:2023-10-16

>输入:

输入的第一行包含一个整数 T,表示 测试用例。

每个测试用例的唯一一行包含 名字。

输出

对于每种情况,输出格式正确的名称。

约束:

  • 1 ≤ T ≤ 100
  • 2 ≤ 名称各部分的长度 ≤ 10 名称的每个部分都包含小写和大写英语的字母 字母(即从"a"到"z",或从"A"到"Z")

    ***Input***
    3
    gandhi
    mahatama gandhi
    mohandas karamchand gandhi
    
    ***Expected Output:***
    Gandhi
    M.Gandhi
    M.K.Gandhi
    
    ***My output:***
    à
    Gandhi
    M.Gandhi
    M.K.Gandhi
    

为什么我在第一行得到"à"符号? 我创建了一个函数格式化程序来为测试用例提供 for 循环。

如果代码太笨重,我提前道歉。

#include<bits/stdc++.h>
using namespace std;
int z;
void formatter(int z){
for(int q = 0;q <= z;q++){
string s;
int count=0;
int k = 0,p = 0,r = 0,t = 0,l = 0,a = 0,x = 0 ;
getline(cin,s);
for(int p = 0;p <= s.size();p++){
if((s[p]==' ')||(p==0)){
count++;
}
}
if(count == 1){
while(r<=s.size()){
s[0] = s[0] -'a' + 'A';
cout << s[r] ;
r++;
}
cout << "n";
}
if(count == 2){
for(int l = 0;l<s.size();l++){
if(l==0){
s[l] = s[l] -'a' + 'A';
cout << s[l] << ".";
a++;
}
if(s[l]==' '){
if(a==1){
++l;
while(l <= s.size()){
if(x == 0){
s[l] = s[l] -'a' + 'A';
}
cout << s[l] ;
a++;
l++;
x++;
}
}
}
}
cout << "n";
}
if(count==3){
for(int i=0;i<s.size();i++){
if(i==0){
s[i] = s[i] -'a' + 'A';
cout << s[i] << ".";
t++;
}
if(s[i]==' '){
if(t==1){
++i;
s[i] = s[i] -'a' + 'A';
cout << s[i] << ".";
t++;
}
else
while(k<=10){
if(k==1){
s[i] = s[i] -'a' + 'A';
}
cout << s[i];
i++;
k++;
}
}

}
}

}
cout << "n";
}
int main(){
cin >> z;
formatter(z);
}

几件事

  • main 中读取计数的 cin 不消耗结束行
  • 格式化程序中的循环是从 0 到在 main 中读取的数字(包括 main)。这是错误的。
  • 考虑将 toupper 转换为 uppper 案例。
  • 考虑分解处理 1、2 和 3 名称的代码。