gpt4 book ai didi

c++ - printf() 函数不起作用

转载 作者:行者123 更新时间:2023-11-30 21:39:36 26 4
gpt4 key购买 nike

我创建了一个 C 程序来打印所有可能的 8 个字符的字符串。但程序内部的printf()函数根本不起作用。这是程序

#include <stdio.h>
#include <string.h>
#include <conio.h>
void ini(void);
void check(void);
void add(void);
static char str[9]; //permuting string
static char test[9]; //test string
static short int c = 1;
void print(char*);
void print(char a[]) {
short int i,ln = (int)(strlen(str)-1);
for(i = 0; i <= ln; i++)
printf("%c",a[i]);
printf("n");
}
void ini() {
//initialzing the strings.
short int i = 0;
for(i = 0; i < 9; i++){
str[i] = 'A';
test[i]= 'z';
}
puts("ini.....");
//initializing done
}
void check() {
//check if the strings 'str' and 'test' are equal
c = strcmp(str, test);
puts("checking..........");
}
void add() {
//this is the heart of the program
short int i = 0;
for( i = 7; i > 0; i--)
{
if((int)str[i] >= (int)'z') {
str[i] = 'A';
str[i-1]++;
}
else if(str[i] < 'z'){
str[i]++;
break;
}
}
puts("adding.......");
}
int main() {
//now we execute the functions above
puts("in main.....");
int i = 0;
while( c != 0 ) //execute the loop while the permuting string 'str' is not equal to the final string 'test'
{
puts("inside while.......");
for(i = 65; i <= 122; i++) { //loop to make the last character of 'str' permute from 'a' to'Z'
str[7] = (char)i;
puts("inside for");
print(str); //print the whole string to the screen
}
add(); //change the next char
check(); //check to see if 'str' has reached it's final point.
}
return 1;
getch();
}

这是结果..............

enter image description here

程序在main()中进入for循环,但不执行print()函数。我尝试过 printf() 但显示了相同的结果。我做错了什么?

最佳答案

您已声明,

static char str[9]; 

因此,str 中的所有元素是 NULL ( \0 ) 现在。那么,

ln = (int)(strlen(str)-1);

在这里,strlen计算字符直到 \0成立。因此,作为 str 中的第一个字符是 \0 , ln将是-1 。在 for loop ,

for(i = 0; i <= ln; i++)

i <= ln条件将失败。

您可以尝试,在 main函数,

str[0] = (char) i; 

或者,调用ini()在调用print(str);之前

但是要小心,你的while loop永远不会破裂!如c永远不会是0 .
因为您的代码不会更改 A 中的第 9 个字符至z所以 strcmp(str, test) 不会 return 0 .

关于c++ - printf() 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31018624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com