【发布时间】:2014-11-03 23:51:33
【问题描述】:
我想用 c 语言编写一个程序,在 while 循环中使用 getline 从标准输入读取一行。
如果该行字符的格式为“number^number”,那么它会计算结果并打印出来。例如,如果用户键入 33^2,那么它将打印 1089。所以我想知道如何检查格式是否正确,否则它会向stderr 返回错误消息,并且用户必须输入另一行。我知道我必须使用strtol 将char 转换为long。
另外,我想知道如何使用getline 来阅读stdin。我只知道怎么用fgets。
这是我尝试过但不起作用的代码部分:
#include <stdio.h>
#include <stdlib.h>
long power(long, long);
long power(long x, long y) {
if (y == 0) {
return 1;
}
else {
return x*power(x, y-1);
}
}
int main(void) {
char *line =(char *) malloc(100*sizeof(char));
char *number1=(char *) malloc(100*sizeof(char));
char *number2=(char *) malloc(100*sizeof(char));
long x;
long y;
printf("User please enter The following format number1^number2\n");
int index;
int length;
while(fgets(line, sizeof line, stdin)!= NULL) { // I want to use getline instead
length=strlen(line);
index = strchr(line,"^")-line; //find the index of "^" in the line
if ((index<0) || (index!=0) || (index!= length-1)) {
fprintf(stderr,"The format is wrong it should be number1^number2\n");
}
else{
for (int i=0; i<index; i++) {
number1[i]=line[i];
}
for (int j=index+1; j<length; j++) {
number1[j]=line[j];
}
x=strtol(number1);
y=strtol(number2);
printf("%ld^%ld = %ld\n",x,y,power(x,y));
}
}
return EXIT_SUCCESS;
}
我还想知道如何在while 的每次迭代中释放我为所有动态数组分配的内存。
在此先感谢
【问题讨论】:
-
while(fgets(line, sizeof line, stdin)!= NULL) {sizeof 的工作方式与您想象的不同。 -
1)
strchr(line,"^")-->strchr(line, '^')2)if ((index<0) || (index!=0) || (index!= length-1)) {条件不好。
标签: c string memory-management malloc getline