Write a program that inputs two string from the keyboard and determines the length of each string. Finally, print each string using twice the length as the field width.
时间: 2024-03-18 18:42:17 浏览: 20
下面是一个C语言程序,实现了从键盘输入两个字符串,并输出每个字符串的长度两倍宽度的功能。
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100];
int len1, len2;
printf("Enter the first string: ");
fgets(str1, 100, stdin);
len1 = strlen(str1) - 1;
printf("Enter the second string: ");
fgets(str2, 100, stdin);
len2 = strlen(str2) - 1;
printf("The first string is: %*s\n", len1 * 2, str1);
printf("The second string is: %*s\n", len2 * 2, str2);
return 0;
}
```
程序先定义了两个字符串数组`str1`和`str2`,然后使用`fgets()`函数从键盘输入两个字符串,并使用`strlen()`函数计算字符串的长度。注意要减去1,因为`fgets()`函数会读入换行符,而换行符不属于字符串的一部分。
最后,使用`printf()`函数输出每个字符串,使用`%*s`格式化输出,其中`*`表示输出的宽度由下一个参数指定,这里是字符串长度的两倍,`s`表示输出字符串。
相关问题
Write a C program that inputs two string from the keyboard and determines the length of each string. Finally, print each string using twice the length as the field width.
Sure, here's the C program that does what you asked for:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
// Input two strings
printf("Enter string 1: ");
scanf("%s", str1);
printf("Enter string 2: ");
scanf("%s", str2);
// Determine length of each string
int len1 = strlen(str1);
int len2 = strlen(str2);
// Print each string using twice the length as the field width
printf("String 1: %*s\n", len1 * 2, str1);
printf("String 2: %*s\n", len2 * 2, str2);
return 0;
}
```
Explanation:
- We declare two char arrays `str1` and `str2` to hold the input strings.
- We use `scanf` function to input the two strings from the keyboard.
- We use `strlen` function to determine the length of each string and store it in `len1` and `len2`.
- We use `printf` function to print each string with twice the length as the field width, using the `%*s` format specifier. The `*` indicates that the field width should be specified as an argument, and we pass `len1 * 2` and `len2 * 2` respectively for the two strings.
Write a program that inputs a string from the keyboard and determines the length of the string. Print the string using twice the length as the field width
Sure, here's an example program in Python:
```python
string = input("Enter a string: ")
length = len(string)
print(f"{string:{length*2}}")
```
This program first prompts the user to enter a string using the `input()` function, and then calculates the length of the string using the `len()` function and stores it in the `length` variable.
Finally, it uses an f-string to print the string with a field width of twice the length of the string, which is achieved by multiplying the length by 2 and passing it as the field width in the f-string. The `:` character is used to specify the field width in the f-string.