尝试接受由空格或行分隔的整数,直到用户键入关键字“end”,此时程序将寻找运算符(+-*/)对输入的整数执行操作。
编译时,我一直收到“指针和整数之间的比较”警告,这很有意义,但我不确定修复它的正确方法。代码中的问题所在有一个注释。
有人能帮助我用正确的语法为第二个SCANF退出迭代,然后转到操作员输入。
谢谢你的帮助!
附言:是的,我知道有更简单的方法来编写程序,但我对C很陌生,我正利用这个机会来练习。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main (void) {
int iarray[100];
char stop[100];
int c = 0;
char action[100];
while (scanf("%d", &iarray[c]) == 1) {
if (scanf("%s", stop) == "end") // the issue is here
break;
else
continue;
c++;
}
if (c == 0) {
printf("error");
return 1;
}
scanf("%s", action);
return 0;
}
最佳答案
第一个问题:如果字符串不等于“end”,请尝试读取字符串,然后使用sscanf
将其转换为整数。(通过strcmp
而不是通过==
进行比较)。
第二个问题:当你读数字的时候,你从来没有接触过c++。继续让它跳过它。
例如,您可以这样做:
char temp[100]
while (scanf("%s", temp) == 1) {
if (0 == strcmp(temp,"end")) // return 0 when both equal...
break;
else{
if( 1 == sscanf(temp,"%d",&iarray[c]))
c++; //number successfully read, increment counter.
else
break; //not end nor number...
}
}
关于c - 第二个scanf识别关键字以退出整数迭代? C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29882906/