乐闻世界logo
搜索文章和话题

How to get ASCII value of string in C

1个答案

1

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

  1. Include the required header file: Use stdio.h for input and output operations.
  2. Read the string: Use scanf to input a string from the user.
  3. Traverse the string: Loop through each character in the string using a loop.
  4. Print ASCII values: For each character in the string, use printf with %d to 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:

shell
h: 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 回复

你的答案