我有一个长度等于52的一维数组,它由随机整数值组成。我想用大写和小写字母打印出带索引的数组。 例如,
index: A B C D E F G H I J K L M N O P Q R S T
array: -1 -1 -1 -1 32 -1 -1 -1 -1 12 -1 -1 -1 -1 20 -1 -1 -1 -1 -1
index: U V W X Y Z a b c d e f g h i ... x y z
array: -1 -1 -1 -1 15 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 ... -1 -1 -1
我尝试使用for
循环到printf("%c\t\r%d\t\b", 'A', -1)
,但是\ b没有向上移动光标。而不是生成我想要的格式(如上所示),我得到了类似下面的内容,
A
-1 B
-1 C
-1 .
. .
. .
.
任何人都知道如何生成上面显示的格式? 提前谢谢。
答案 0 :(得分:0)
在这里,我只向您提供了在turbo C中编译的C语言程序所需的格式示例。
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int j=96;
clrscr();
for(int i=1;i<=52;i+=2)
{
gotoxy(i,1);
printf("%c",j+=1);
gotoxy(i,2);
printf("%d ",random(2));
}
j=96;
for(i=1;i<=52;i+=2)
{
gotoxy(i,3);
printf("%c",j+=1);
gotoxy(i,4);
printf("%d ",random(2));
}
getch();
}
答案 1 :(得分:0)
以下内容不依赖于ASCII,非常便携。
只需在另一个数组中查找索引显示字符。
static const char index[52] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int A[52] = { -1, -1, -1, -1, 32, -1, -1, -1, -1, 12, -1, -1, -1, -1, 20, -1 ...};
int i;
fputs("index: ", stdout);
for (i=0; i<52; i) {
printf(" %c", index[i]);
}
fputs("\n", stdout);
fputs("array: ", stdout);
for (i=0; i<52; i) {
printf(" %2d", A[i]);
}
fputs("\n", stdout);
答案 2 :(得分:0)
C和C ++没有任何屏幕或控制台的概念,它们只能看到没有固有显示特性的字节流。有ncuses之类的第三方API可以帮助您实现这一目标。
一种方法,使用cursor movement的ANSI转义序列,其中ESC [y; xH将光标移动到y行,col x,左上角为{1,1}。
printf("\033[%d;%dH", row, col);
在Windows中你可以尝试,
使用SetConsoleCursorPosition。 SetConsoleCursorPosition
MSDN库的同一部分还有许多其他功能。其中一些也可能有用。
否则,您可以将打印限制为一行的特定索引量,您可以尝试下面的代码。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int main() {
const char charIndex[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const unsigned int counter = 133;
const unsigned int hBuffer = 14; // max number of indexes in a line
unsigned int row,j;
unsigned int arrIndex = 0,yetToPrintcount = counter,htempBuffer;
// Nof of Rows needed to print the counter
unsigned int noOfRows = ( counter / hBuffer );
// if no reminder means no trailing values less than hBuffer to print
if ( counter % hBuffer == 0 ) noOfRows--;
srand(time(NULL)); // For random numbers
for ( row = 0 ; row <= noOfRows; ++row)
{
// For printing the trailing numbers
// which are less than the h_buffer size
if ( yetToPrintcount < hBuffer )
htempBuffer = yetToPrintcount;
else
htempBuffer = hBuffer;
// printing the index first
printf("index: ");
for (j = 0; j < htempBuffer; ++j){
// circular printing of index
if( arrIndex == (sizeof(charIndex) / sizeof(char))-1 ) arrIndex = 0;
printf(" %c", charIndex[arrIndex++]);
}
printf("\n");
// printing the array random values
printf("array: ");
for (j = 0; j < htempBuffer; ++j)
printf(" %d", rand()%10); // Prints Random numbers between 0 to 9
printf("\n");
yetToPrintcount -= hBuffer;
}
return 0;
}