希望这个程序输出“Digi”,但为什么它输出“Dig)tal孟加拉国”。
谁能解释一下吗?
#include<stdio.h>
int main(){
char str[120]="Digital Bangladesh";
int n;
n=strlen(str);
printf("%d \n",n);
str[4]="\0";
printf("%s",str);
return 0;
}
最佳答案
我在评论中给出了基本解释,并稍微改进了您的代码(将 "\0"
替换为 '\0'
并包含 string.h
for strlen()
)。
#include <stdio.h>
#include <string.h>
int main() {
char str[120] = "Digital Bangladesh";
int n = strlen(str); // can combine declaration and assignment into a single statement;
// this will assign the actual length of string str to n
printf("%d \n", n);
str[4] = '\0'; // shouldn't be "\0" since anything in double quotes will be a string and not a character
// you are assigning 5th character (4th index + 1) of str to NULL ('\0') terminator character;
// now str will have content "Digi"
printf("%s", str);
return 0;
}
关于c - 这个程序的输出是什么?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56911660/