![](/img/trans.png)
[英]Why does the C/++ scanf function need referenced variables as arguments?
[英]Why multiple arguments in scanf() function in c crash the app?
我真的无法理解以下scanf()的语法
该程序的目的是读取数学输入,例如:6x + 7y + 8z = 2(x3次)
然后输出一个保存输入数值的数组。
成功输入后,应用程序崩溃
尽管编译器未显示任何错误或警告
#include <stdio.h>
int main()
{
int number[3][4],i,j;
char vch[3][4];
for(i=0;i<3;i++){
scanf("%d%c%d%c%d%c%c%d",&number[i][0],&vch[i][0],&number[i][1],&vch[i][1],&number[i][2],&vch[i][2],&vch[i][3],&number[i][3]);
printf("\n");
}
for(i=0;i<3;i++)
for(j=0;j<4;j++)
printf("%d",number[i][j]);
return 0;
}
要阅读显示的方程式,您确实需要在第一组数字之间读取两个字符(而不是一个)。 所以你想做
#include <stdio.h>
int main()
{
int number[3][4],i,j;
char vch[3][6];
for(i=0;i<3;i++){
printf("enter equation %d:\n", i);
scanf("%d %c %c %d %c %c %d %c %c %d",&number[i][0], &vch[i][0], &vch[i][1], \
&number[i][1], &vch[i][2], &vch[i][3], \
&number[i][2], &vch[i][4], &vch[i][5], \
&number[i][3]);
}
for(i=0;i<3;i++) {
for(j=0;j<4;j++)
printf("%4d ",number[i][j]);
printf("\n");
}
return 0;
}
输出:
enter equation 0:
2x+3y+4z=0
enter equation 1:
2x+5y+10z=-15
enter equation 2:
5x+7y+9z=3
2 3 4 0
2 5 10 -15
5 7 9 3
编辑一个不使用scanf
并处理各种其他输入的改进程序,如下所示:
#include <stdio.h>
#include <string.h>
int interpret(char* s) {
// interpret the string as a number
// if there is only a sign, return +1 or -1 as appropriate
int it;
if(sscanf(s, "%d", &it) == 1) return it;
// look for just a sign with no number
if( strstr(s, "-") > 0) return -1;
return 1;
}
void squeezeWhite(char* s) {
// remove all spaces
char *t = s;
int ii = 0;
while(*t !='\0') {
if (*t != ' ') s[ii++] = *t;
t++;
}
s[ii] = '\0';
}
void tokenize(char *buf, int *arr) {
char *temp;
int it;
squeezeWhite(buf);
temp = strtok(buf, "xyz");
// handle the case of nothing in front of x:
if(temp == buf + 1) {
arr[0] = 1;
arr[1] = interpret(temp);
}
else {
arr[0] = interpret(temp);
temp = strtok(NULL, "xyz");
arr[1] = interpret(temp);
}
temp = strtok(NULL, "xyz");
arr[2] = interpret(temp);
temp = strtok(NULL, "=");
arr[3] = interpret(temp);
}
int main()
{
int number[3][4],i,j;
char vch[3][6];
char buffer[100];
for(i=0;i<3;i++){
printf("enter equation %d:\n", i);
fgets(buffer, 100, stdin);
tokenize(buffer, number[i]);
}
for(i=0;i<3;i++) {
for(j=0;j<4;j++)
printf("%4d ",number[i][j]);
printf("\n");
}
return 0;
}
输入/输出示例:
enter equation 0:
-x+y+z=1
enter equation 1:
2x + 3 y + 4 z = 7
enter equation 2:
+2x+2y+2z=+2
-1 1 1 1
2 3 4 7
2 2 2 2
如您所见,即使没有数字(正号或负号),它也可以正常处理系数。 当您的用户可能不符合您的输入规范时,我在此处显示的基本思想(逐步处理输入)是一个好主意。 它比读取scanf
健壮得多, scanf
将是第一个障碍。 它确实涉及编写一些“辅助函数”。 通常就是这样的...
尝试这个
scanf("%d %c %c %d %c %c %d %c %c %d",&number[i][0],&vch[i][0],&vch[i][1] &number[i][1],&vch[i][2],&vch[i][3],&number[i][2],&vch[i][4],&vch[i][5],&number[i][3]);
在%c
之前有一个额外的空间,可以吃掉上一个scanf
留下的换行符\\n
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.