scanf,gets输入问题,求各位指教
[code=C/C++][/code]/*括号配对问题
/*
描述
现在,有一行括号序列,请你检查这行括号是否配对。
输入
第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串)
,测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
输出
每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
样例输入
3
[(])
(])
([[]()])
样例输出
No
No
Yes
*/
#include <stdio.h>
int main()
{
int N;
int i, j, k;
char S[100];
scanf("%d", &N);
while (N--)
{
scanf("%s", S);
for (i = 0; S[i] != '\0'; i++)
{
k = i;
}
if ( S[0] == '(' )
{
S[k] == ')' ? printf("Yes\n") : printf("No\n");
}
else
{
if ( S[0] == '[' )
{
S[k] == ']' ? printf("Yes\n") : printf("No\n");
}
else
{
printf("N0\n");
}
}
}
return 0;
}
这是我写的一个程序,为什么我输入次数N时,我用for循环不行,总是输入一组字符串就直接结束,用while循环即现在写法时可以输入N次???
[解决办法]
为啥我可以呢??
你是说的这个地方吗?
for(N;N>0;N-- )
{
// Your codes
}
并且,呵呵,有严重的bug,像()(,这样的字符串,输出该为No,但是~~
[解决办法]
好像acm里有这么一个题目,用栈试试
[解决办法]
刚好之前做过这个题,也是做了很久才搞定,记得给分啊!
- C/C++ code
#include <stdio.h>#include <string.h>//当'('和')','['和']'个数配对时调用 返回值:0:配对成功 -1:不成功int Peidui(char *p) { int xx,yy;//记录'('和‘[’的个数 char *ptmp; ptmp=p; while( *ptmp !='\0') { xx=yy=0; if( *ptmp == '(' ) { xx=1; } else if( *ptmp == '[') { yy=1; } else return -1; if(xx) //如果第一个字符为'(' { while((*(++ptmp) !='\0') && (xx != 0)) //直到找到配对的')' { if(*ptmp == '(') xx++; if(*ptmp == '[') yy++; if(*ptmp == ')') //当xx为负值时表示有')'出现在'('之前 { xx--; if(xx<0) return -1; } if(*ptmp == ']') { yy--; if(yy<0) return -1; } } if(yy) //()里面有[]不配对的情况 { return -1; } } if(yy) { while((*(++ptmp) !='\0')&&(yy != 0)) { if(*ptmp == '(') xx++; if(*ptmp == '[') yy++; if(*ptmp == ')') { xx--; if(xx<0) return -1; } if(*ptmp == ']') { yy--; if(yy<0) return -1; } } if(xx) { return -1; } } } return 0; }int main(){ int testNum,res,i=0,j=0; int x=0,y=0,len; char testData[10010]; scanf("%d",&testNum); if((testNum<=0) || (testNum>100)) return 0; for(i=0;i<testNum;i++) { scanf("%s",testData); len=strlen(testData); if((len>=10000) && (len==0)) { i--; continue; } j=0; while(testData[j] !='\0') //检查并记录输入的字符 { switch(testData[j]) { case '(':x++;break; case ')':x--;break; case '[':y++;break; case ']':y--;break; default:return 0; //不符合输入规则就退出 } j++; } if(x==0 && y==0) { res=Peidui(testData); if(res==0) printf("Yes\n"); else printf("No\n"); } else printf("No\n"); x=y=0; //注意这里要赋值为0 } return 0;}