C语言如何获取字符串单个元素?为何提取buf前7字符输出异常?
Hey there! Let's break down your problem step by step—first why your printf output is messed up, then how to properly access each element of a string in C.
The core issue here is how you're using printf with the %s format specifier.
%s is designed to print null-terminated strings—meaning it reads bytes starting from the given address until it hits a '\0' (the null character that marks the end of a C string). But in your code, you're passing the address of a single char variable (like &A) to %s.
Since your A through G are global variables, they're stored consecutively in memory. When printf("%s", &B) runs, it starts reading at B's address, grabs 'e', then keeps going to C ('l'), D ('l'), E ('o'), F (space), G ('W'), and then continues reading whatever is in the memory after G until it finds a '\0'. That's why you're seeing those extra characters tacked on.
To print a single character, you need to use the %c format specifier instead of %s. Here's your corrected code:
#include <stdio.h> char buf[20]="Hello World"; char A,B,C,D,E,F,G; int main() { A=buf[0]; B=buf[1]; C=buf[2]; D=buf[3]; E=buf[4]; F=buf[5]; G=buf[6]; // Use %c to print individual chars printf("1 %c,2 %c,3 %c,4 %c,5 %c,6 %c,7 %c", A,B,C,D,E,F,G); return 0; }
This will output exactly what you expected: 1 H,2 e,3 l,4 l,5 o,6 ,7 W.
There are a few common, reliable ways to get each character from a C string:
- Array Indexing: Since a string is just a
chararray, you can directly access elements withbuf[i](indexes start at 0). You can loop until you hit the null terminator, or usestrlen()to get the string length first:#include <stdio.h> #include <string.h> // Needed for strlen() int main() { char buf[20] = "Hello World"; int length = strlen(buf); for (int i = 0; i < length; i++) { printf("%d %c, ", i+1, buf[i]); } return 0; } - Pointer Traversal: Use a
charpointer to iterate through the string. The pointer starts at the first character, and you increment it until you hit'\0':#include <stdio.h> int main() { char buf[20] = "Hello World"; char *ptr = buf; int count = 1; while (*ptr != '\0') { printf("%d %c, ", count++, *ptr); ptr++; } return 0; } - Direct Assignment (like your original code): If you just need specific elements, you can assign them directly to variables as you did—just make sure to use the right format specifier when printing!
内容的提问来源于stack exchange,提问作者xiao liu

