C 嵌套for/while循环和数组,从数组中过滤出数字 int main(无效) { int i,j=0,k;//初始化 字符方程[100];//输入是一个字符串(我想是?) int data[3];//只需要获取3个数字 printf(“输入公式:”); fgets(方程式,100,stdin);//对fgets()不太确定 对于(i=0;i
代码中存在一些问题:C 嵌套for/while循环和数组,从数组中过滤出数字 int main(无效) { int i,j=0,k;//初始化 字符方程[100];//输入是一个字符串(我想是?) int data[3];//只需要获取3个数字 printf(“输入公式:”); fgets(方程式,100,stdin);//对fgets()不太确定 对于(i=0;i,c,arrays,loops,while-loop,nested,C,Arrays,Loops,While Loop,Nested,代码中存在一些问题: (i=0;i
int main(void)
{
int i,j=0,k; //initialization
char equation[100]; //input is a string (I think?)
int data[3]; //want only 3 numbers to be harvested
printf("Enter an equation: ");
fgets(equation, 100, stdin); //not so sure about fgets()
for (i = 0; i < equation[100]+1; i++) { //main loop which combs through
//"equation" array and attempts
//to find int values and store
while (j <= 2) { //them in "data" array
if (isdigit(equation[i])) {
data[j] = equation[i]
j++;
}
}
if (j == 2) break;
}
for (k = 0; k <= 2; k++) { //this is just to print the results
printf("%d\n", data[k]);
}
return 0;
}
data[j] = equation[i];
我想您想将数字存储在方程中
到数据中
break;
应删除
这个break;
语句将跳出而循环,结果是您将方程中的最后一位存储到数据[0]
(假设您已切换数据和方程,如#2中所述)
如果您想要方程
中的前三位,您应该执行以下操作
int main(void)
{
int i,j=0,k; //initialization
char equation[100]; //input is a string (I think?)
int data[3]; //want only 3 numbers to be harvested
printf("Enter an equation: ");
fgets(equation, 100, stdin); //not so sure about fgets()
for (i = 0; i < equation[100]+1; i++) { //main loop which combs through
//"equation" array and attempts
//to find int values and store
while (j <= 2) { //them in "data" array
if (isdigit(equation[i])) {
data[j] = equation[i]
j++;
}
}
if (j == 2) break;
}
for (k = 0; k <= 2; k++) { //this is just to print the results
printf("%d\n", data[k]);
}
return 0;
}
data[j] = equation[i];
通过以下方式进行测试:
#include <ctype.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int i,j,k;
char equation[100];
int data[3];
int equ_len;
printf("Enter an equation: ");
fgets(equation, 100, stdin);
equ_len = strlen(equation);
j = 0;
for (i = 0; i < equ_len; i++) {
if (j <= 2 && isdigit(equation[i])) {
data[j] = equation[i];
j++;
}
if (j > 2) break;
}
for (k = 0; k <= 2; k++) {
printf("%c\n", data[k]);
}
return 0;
}
你不希望数组中有0吗?除非输入字符串是0!我总是得到0,而不是实际字符串:(这行“for(I=0;I$ ./a.out
Enter an equation: 1 + 2 + 3
1
2
3