In C programming, to obtain the ASCII values of each character in a string, you can iterate through the string and use the %d format specifier to print the integer value of each character. Here is a detailed explanation of this process, along with a concrete code example.
Steps
- Include the required header file: Use
stdio.hfor input and output operations. - Read the string: Use
scanfto input a string from the user. - Traverse the string: Loop through each character in the string using a loop.
- Print ASCII values: For each character in the string, use
printfwith%dto print its ASCII value.
Example Code
Below is a simple example code demonstrating how to implement the above steps:
c#include <stdio.h> int main() { char str[100]; // Assuming string length does not exceed 100 printf("Enter a string: "); scanf("%s", str); // Read the string int i = 0; printf("ASCII values of each character in the string:\n"); while (str[i] != '\0') { // Traverse the string until the null terminator printf("%c: %d\n", str[i], str[i]); // Print the character and its ASCII value i++; } return 0; }
Running Example
Suppose the user enters hello, the program's output will be:
shellh: 104 e: 101 l: 108 l: 108 o: 111
This method is straightforward and effectively retrieves the ASCII values of each character in the string. You can handle more complex input scenarios as needed, such as strings containing spaces or special characters.
2024年7月30日 00:28 回复