[英]printing the array in reverse order-why is this wrong in C++?
I want to print the array in the reverse order.我想以相反的顺序打印数组。 And I can't understand why this is impossible.
我不明白为什么这是不可能的。
#include<stdio.h>
int main(){
int str[100];
int len=0;
printf("Array: ");
scanf("%s",str);
while(str[len]!=0)
len++;
for(int i=len-1;i>=0;i--)
printf("%c",str[i]);
return 0;
}
This isn't working for a few reasons:这不起作用有几个原因:
Let's break things down into parts that do each job.让我们把事情分解成完成每项工作的部分。 First: printing an array in reverse:
第一:反向打印数组:
void print_in_reverse(int* ptr, int len) {
for(int i = len - 1; i >= 0; i--) {
printf("%i ", ptr[i]);
}
printf("\n");
}
This will print an array of ints in reverse based on the length of the array.这将根据数组的长度反向打印一个整数数组。
The second task is reading in the array.第二个任务是读取数组。 We need to check for
EOF
, or the End of File, because if someone presses Ctrl-D
(or Ctrl-Z
in windows) in the terminal, that will indicate that there's no more input and scanf
will return EOF
.我们需要检查
EOF
或文件结尾,因为如果有人在终端中按下Ctrl-D
(或 Windows 中的Ctrl-Z
),这将表明没有更多输入并且scanf
将返回EOF
。
int read_in_array(int* arr, int max_len) {
int num_read = 0;
for(int i = 0; i < max_len; i++) {
// Read into the ith element
int flag = scanf("%i", &(arr[i]));
if(flag == EOF) {
break;
}
num_read++;
}
return num_read;
}
This will read in up to max_len
ints.这将最多读取
max_len
整数。 It will also return the number it read successfully.它还将返回它成功读取的数字。
Now, we can put them together:现在,我们可以将它们放在一起:
int main() {
int arr[100];
int num_read = read_in_array(arr, 100);
print_in_reverse(arr, num_read);
}
When I compile and run it, I get the following output:当我编译并运行它时,我得到以下 output:
11:46:09 perez ~$ g++ test.cpp
11:46:10 perez ~$ ./a.out
10
20
30
30 20 10
I entered 10 20 30
, and then pressed Ctrl+D
to indicate that I had no more numbers.我输入
10 20 30
,然后按Ctrl+D
表示我没有更多数字了。 The program then responded with 30 20 10
然后程序以
30 20 10
响应
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.