C 通过gets对输入文本中的符号和空行进行计数
程序应打印输入文本中的空行数和某些运算符。我已经解决了空行的问题,但我面临着与对手的问题。我想是因为休息时间有问题。如果有任何好的修改代码的想法,我将不胜感激。抱歉,如果这样的线程已经存在,但我检查了,无法获得解决方案。提前谢谢C 通过gets对输入文本中的符号和空行进行计数,c,C,程序应打印输入文本中的空行数和某些运算符。我已经解决了空行的问题,但我面临着与对手的问题。我想是因为休息时间有问题。如果有任何好的修改代码的想法,我将不胜感激。抱歉,如果这样的线程已经存在,但我检查了,无法获得解决方案。提前谢谢 char c,line[300]; int emptyLine = 0; int operators = 0; printf("Input your text and press ctr+Z on a new line when done: \n")
char c,line[300];
int emptyLine = 0;
int operators = 0;
printf("Input your text and press ctr+Z on a new line when done: \n");
while(gets(line)) {
int i = 0;emptyLine++;
for (i = 0; i < strlen(line); i++) {
if(line[i] == '+'|| line[i] == '-' || line[i] == '/' || line[i] == '*' || line[i] == '%')
{
operators++;
}
if (line[i] != '\n' && line[i] != '\t' && line[i] != ' ') {
emptyLine--;
break;
}
}
}
printf("The number of empty lines is: %d",emptyLine);
printf("\nThe number of opperators is: %d",operators);
charc,第[300]行;
int-emptyLine=0;
int运算符=0;
printf(“输入文本,完成后在新行上按ctr+Z:\n”);
while(获取(行)){
int i=0;emptyLine++;
对于(i=0;i
尝试以下方法:
char c,line[300];
int emptyLine = 0;
int operators = 0;
printf("Input your text and press ctr+Z on a new line when done: \n");
while(gets(line)) {
bool isEmpty = true; // Assume empty line
for (int i = 0; 0 != line[i]; i++) {
if (!isspace(line[i])) {
isEmpty = false; // Line not empty
}
if (line[i] == '+'|| line[i] == '-' || line[i] == '/' || line[i] == '*' || line[i] == '%') {
operators++;
}
}
if (isEmpty) {
emptyLine += 1;
}
}
printf("The number of empty lines is: %d",emptyLine);
printf("\nThe number of operators is: %d",operators);
如果一行在运算符前面有空格,则由于中断,您不会计算运算符。虽然尝试得很好,但当我键入一些文本,后跟enter和enter+ctrZ时,它会返回空行的“-”值,因为它会检查每个元素,并将空行的值减少1。我不希望这样:)我猜断裂也是问题的主要原因,但移除并不能解决问题。效果很好!谢谢!:)永远不要使用
获取
!它绝对不会进行长度检查,因此如果不打开安全漏洞,就不可能使用它。事实上,许多注意到正在使用的get
的系统在运行程序时会打印警告。相反,使用fgets
和stdin
作为文件指针<代码>字符行[100];fgets(生产线、尺寸(生产线)、标准DIN)代码>。