如何读取数组中的随机数int

我想将空格分隔的整数读入一个数组,当我按回车时它应该在任何时间点停止读取,如何实现这个程序的循环请帮我解决这个问题。 我试过下面的代码,但它不起作用。还有如何再次阅读。

#include int main() { int arr[30]; int j=0; while(1) { int d; scanf("%d",&d); arr[j++]=d; if(d=='\n')break; } return 0; } 

提前致谢

您的问题是scanf会在查找下一个项目时自动跳过所有空格(空格,制表符,换行符)。 您可以通过专门要求读取换行符来区分换行符和其他空格:

 int main() { int arr[30]; // results array int cnt = 0; // number of results while (1) { // in the scanf format string below // %1[\n] asks for a 1-character string containing a newline char tmp[2]; // buffer for the newline int res = scanf("%d%1[\n]", &arr[cnt], tmp); if (res == 0) { // did not even get the integer // handle input error here break; } if (res == 1) { // got the integer, but no newline // go on to read the next integer ++cnt; } if (res == 2) { // got both the integer and newline // all done, drop out ++cnt; break; } } printf("got %d integers\n", cnt); return 0; } 

这种方法的问题在于它只识别整数后面的换行符,并且会静默跳过只包含空格的行(并从下一行开始读取整数)。 如果这是不可接受的,那么我认为最简单的解决方案是将整行读入缓冲区并解析该缓冲区中的整数:

 int main() { int arr[30]; // results array int cnt = 0; // number of results char buf[1000]; // buffer for the whole line if (fgets(buf, sizeof(buf), stdin) == NULL) { // handle input error here } else { int pos = 0; // current position in buffer // in the scanf format string below // %n asks for number of characters used by sscanf int num; while (sscanf(buf + pos, "%d%n", &arr[cnt], &num) == 1) { pos += num; // advance position in buffer cnt += 1; // advance position in results } // check here that all of the buffer has been used // that is, that there was nothing else but integers on the line } printf("got %d integers\n", cnt); return 0; } 

另请注意,当行上有30个以上的整数时,上述两种解决方案都将覆盖结果数组。 如果第二个解决方案比输入缓冲区更长,那么第二个解决方案也会使某些输入行未读。 根据输入的来源,这些都可能是在实际使用代码之前需要修复的问题。

方法1:使用scanf()的返回值并输入一个字符一旦完成(你的问题不需要这个读取直到换行不起作用,但这是其中一种方法)

 int d; while(scanf("%d",&d) == 1) { arr[i] = d; i++; } 

方法2:使用fgets()读取行并使用strok()atoi()解析行,如图所示

 char arr[100]; fgets(arr,sizeof(arr),stdin); char *p =strtok(arr, " "); while(p != NULL) { int d = atoi(p); arr[i++] = d; p = strtok(NULL," "); } 

一个好方法是使用getchar()和一个字符通过检查ASCII值来检查程序中的ENTER

 while(1) { char d; d=getchar(); if(d==13 || d==10) break; arr[j++]=d-'0'; } 

它会在你按下回车后立即终止。 关于这篇post已经提供了更多的讨论

scanf("%d"...首先从占用前导空格开始。要检测'\n' ,代码应该在调用scanf("%d"...之前扫描前导空格scanf("%d"...

要在'\n'发生时终止输入, 首先要开始寻找它。 建议使用getchar()

以下代码处理OP目标和:
*以\n开头的行
*超过N int
* EOF和非数字输入

 #include #include #define N (30) int main(void) { int arr[N]; int j = 0; for (j = 0; j < N; j++) { // Don't read too many int ch; while ((ch = getchar()) != '\n' && isspace(ch)); if (ch == '\n') { break; } // put back ch ungetc(ch, stdin); int cnt = scanf("%d", &arr[j]); if (cnt != 1) { break; // Stop if input is EOF or non-numeric } } printf("%d\n", j); return 0; }