gpt4 book ai didi

不能打破 while 循环。读取未定义的数组大小

转载 作者:太空宇宙 更新时间:2023-11-04 04:23:26 28 4
gpt4 key购买 nike

我有这个字母和数字序列,其中字母总是这四个:s、S、m、M。数字可以有任何值。由于没有给出序列的大小,我不能使用 for 循环,所以我决定使用 while 循环,但我在中断循环时遇到了问题。

一些输入示例是:

12 s 80 s 3 m 12 M 240 S 8 m 30 s 240 s 1440 S 8 m 18 s 60 M

5 m 120 s 30 s 360 S 6 M 5 s 42 S 36 M 8 m 66 M 3240 S 14 m

到目前为止,这是我的代码:

#include <stdio.h>

int main () {

int n[100], i = 0;
char x[100];

while(x[i] != '\n')
{
scanf(" %d %c", &n[i], &x[i]);
printf("%d %c ", n[i], x[i]);
i++;
}

return 0;
}

关于如何打破循环并将所有这些值正确保存在数组中有什么技巧吗?

最佳答案

像这样

#include <stdio.h>

int main(void){
int n[100], i, j;
char x[100];

do {
for(i = 0; i < 100; ++i){
int ch;
while((ch = getchar()) != EOF && ch != '\n'){//check newline
if(ch == '-' || '0' <= ch && ch <= '9'){
ungetc(ch, stdin);//back to stream a character
break;
}
}
if(ch == EOF || ch == '\n')
break;
if(2 != scanf("%d %c", &n[i], &x[i])){
fprintf(stderr, "invalid format.\n");
i = 0;//End the outer do-while loop
break;
}
}
//print
for(j = 0; j < i; ++j){
printf("(%d, %c)", n[j], x[j]);
}
printf("\n");
} while(i != 0);//End with empty line
}

#include <stdio.h>

#define DATA_MAX_LEN 100

int main(void){
int n[DATA_MAX_LEN], i, len, loop_end;
char x[DATA_MAX_LEN], newline[2], ch;

while(scanf("%1[\n]", newline) != 1){//End with empty line(only newline), Need EOF check
for(loop_end = len = i = 0; i < DATA_MAX_LEN && !loop_end; ++i){
//format: integer character[space|newline]
if(scanf("%d %c%c", &n[i], &x[i], &ch) != 3)
loop_end = printf("invalid format.\n");
else if(ch == '\n')
loop_end = len = ++i;
else if(ch != ' ')
loop_end = printf("invalid format.\n");
}
for(i = 0; i < len; ++i){
printf("%d %c ", n[i], x[i]);
}
printf("\n");
}
}

关于不能打破 while 循环。读取未定义的数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43958519/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com