我对C很陌生,我在语法和指针方面有一些问题。
有一个数组
int ar[6] = {2, 3, 6, 7, 1, 9};
还有一个指针
int* p = ar;
在输出中,我不想打印出指针指向的数字,而是想在该数字的下面有一个^。我想让它随着指针移动而移动。
我希望输出像这样:
The array = {2 3 6 7 1 9}
^
但是我不知道如何让它跳过" the array ={"部分
我只是像这样打印数组
printf("The array = { ");
for(int i=0; i< 6;i++){
printf("%d ", ar[i]);
}
我用getchar()移动指针,所以来自用户的输入。
p = &a[0];
c = getchar();
if(c =='a'){
if(p == &ar[0]){
p--;
}
if( c=='d'){
p++;
}
我不知道是否有更简单的方法来做这件事。
你可以试试-
#include <stdio.h>
#include <string.h>
int main(){
int ar[6] = {2, 3, 6, 7, 1, 9};
int* p = ar+2;
const char *s="int ar[6] = {"; // starting part of string
printf("%s",s); // print string
for(int i=0; i< 6;i++){
printf("%d ", ar[i]); // print array elements
}
printf("}n"); // get to next line
size_t n=strlen(s); // calculate length of declaration part
for(int i=0;i<n;i++)
printf(" "); // print number of spaces
for(int i=0; i< 6;i++){
if(p==ar+i){
printf("^"); // if true print ^
break;
}
else
printf(" "); // if not then print 2 spaces
}
}
输出细化打印数字的部分。
// Use variables to help match the output
char const* prefix1 = "The array = { ";
char const* prefix2 = " ";
// Print the numbers first.
printf("%s", prefix1);
for(int i=0; i< 6;i++){
printf("%d ", ar[i]);
}
printf("n");
下面是打印^
符号的代码。您可以根据a
的元素地址测试指针值,并打印^
符号。当数字不限于一个数字时,这将有效。
// Print the the ^ symbol at the right place
printf("%s", prefix2);
for(int i=0; i< 6;i++) {
if ( p == &ar[i] ) {
printf("^");
break;
}
// Print the number to the temporary buffer.
// If the length of the buffer is 6, we need to print 6 spaces.
char temp[20];
sprintf(temp, "%d ", a[i]);
int len = strlen(temp);
for ( int j = 0; j < len; ++j )
{
temp[j] = ' ';
}
printf("%s", temp);
}
printf("n");
根据@Barmar在评论中提到的,我将这样做。
int main() {
const char text[] = "The array = { ";
int print_offset[6];
int ar[6] = {2, 3, 6, 7, 1, 9};
char c;
int i;
print_offset[0] = printf("%s", text) + 1;
for(i=0; i<5;i++){
print_offset[i+1] = print_offset[i] + printf("%d ", ar[i]);
}
printf("%d }n", ar[i]);
i = 0;
while(1) {
c = getchar();
if(c =='a'){
i++;
i %= 6;
printf("%*cr", print_offset[i], '^');
}
else if(c=='d'){
i--;
if(i < 0)
i = 5;
printf("%*cr", print_offset[i], '^');
}
}
}
在print_offset
中,由于printf的返回值,我存储了我必须打印^
的偏移量。然后,我在printf中使用*
宽度说明符来在先前计算的偏移量处打印'^'。
int
,该代码也可以工作。