在C中使用while(scanf)时出现代码块错误
我在下面附上了一段代码,它在在线编译器中工作得非常好,但在使用C时在代码块编译器中无法工作。我还附上了屏幕截图在C中使用while(scanf)时出现代码块错误,c,compiler-errors,runtime-error,codeblocks,C,Compiler Errors,Runtime Error,Codeblocks,我在下面附上了一段代码,它在在线编译器中工作得非常好,但在使用C时在代码块编译器中无法工作。我还附上了屏幕截图 #include <stdio.h> int main() { int i = 0; int array[100]; while(scanf("%d",&array[i])>0) { i++; } for(int j=0;j<i;j++) { printf("%d
#include <stdio.h>
int main() {
int i = 0;
int array[100];
while(scanf("%d",&array[i])>0)
{
i++;
}
for(int j=0;j<i;j++)
{
printf("%d ",array[j]);
}
return 0;
}
#包括
int main(){
int i=0;
整数数组[100];
而(scanf(“%d”)和数组[i])>0
{
i++;
}
对于(int j=0;j没有错误,您的while
循环将继续进行,直到输入无效的输入,您对输入的数量没有限制,因此它将继续取值,这可能会在以后成为一个问题,因为您的容器只有100int
s的空间
它在一些在线编译器上停止,因为它们使用stdin输入的方式,它基本上是一次性读出
示例:
它停止,有一次stdin
读数
它不会停止,具有类似于输入/输出的控制台
因此,如果您想停止在给定数量的输入,您可以执行以下操作:
//...
while (i < 5 && scanf(" %d", &array[i]) > 0)
{
i++;
}
//...
//...
while (i < 100 && scanf("%d", &array[i]) > 0) { // still need to limit the input to the
// size of the container, in this case 100
i++;
if (getchar() == '\n') { // if the character is a newline break te cycle
// note that there cannot be spaces after the last number
break;
}
}
//...
以前的版本缺少一些错误检查,因此要获得更全面的方法,您可以执行以下操作:
#include <stdio.h>
#include <string.h> // strcspn
#include <stdlib.h> // strtol
#include <errno.h> // errno
#include <limits.h> // INT_MAX
int main() {
char buf[1200]; // to hold the max number of ints
int array[100];
char *ptr; // to iterate through the string
char *endptr; // for strtol, points to the next char after parsed value
long temp; //to hold temporarily the parsed value
int i = 0;
if (!fgets(buf, sizeof(buf), stdin)) { //check input errors
fprintf(stderr, "Input error");
}
ptr = buf; // assing pointer to the beginning of the char array
while (i < 100 && (temp = strtol(ptr, &endptr, 10)) && temp <= INT_MAX
&& errno != ERANGE && (*endptr == ' ' || *endptr == '\n')) {
array[i++] = temp; //if value passes checks add to array
ptr += strcspn(ptr, " ") + 1; // jump to next number
}
for (int j = 0; j < i; j++) { //print the array
printf("%d ", array[j]);
}
return EXIT_SUCCESS;
}
#包括
#包括//strcspn
#包括//strtol
#包括//errno
#包括//INT\u MAX
int main(){
char buf[1200];//用于保存最大整数
整数数组[100];
char*ptr;//遍历字符串
char*endptr;//对于strtol,指向解析值后的下一个字符
long temp;//临时保存已解析的值
int i=0;
如果(!fgets(buf,sizeof(buf),stdin)){//检查输入错误
fprintf(标准“输入错误”);
}
ptr=buf;//指定指向字符数组开头的指针
而(i<100&(温度=strtol(ptr和endptr,10))&&temp那么,在不知道数组在代码块中的大小的情况下,我应该如何获得数组?@HaamithSulthan,你的意思是你不知道用户输入了多少值?是的,这是我面临的问题。@HaamithSulthan我在答案中添加了两个解决方案,一个更简单,另一个更全面。