我如何编写函数:
a) 对字符串的长度求和(并打印),并在附加两个字符串之前检查字符串的总和是否小于 70(如果大于 70,则会出现空消息)
b) 在这种情况下如何使用 fgets?
c)我还尝试打印出原始的两个字符串和组合字符串。
这是我到目前为止所拥有的..但我对如何继续感到困惑???
#include <stdio.h>
#include <string.h>
int main()
{
char a[70], b[50];
printf("Enter the first string\n");
gets(a);
printf("Enter the second string\n");
gets(b);
strcat(a,b);
printf("String obtained on concatenation is %s\n",a);
最佳答案
#include <stdio.h>
#include <string.h>
#define BUFFERSIZE 1024
int main() {
char buffer_a[BUFFERSIZE];
char buffer_b[BUFFERSIZE];
char *concat;
printf("Enter the first string: \n");
if(fgets(buffer_a, BUFFERSIZE, stdin)){
char *p = strchr(buffer_a, '\n');
if (p){
*p = '\0';
}
}
printf("Enter the second string: \n");
if(fgets(buffer_b, BUFFERSIZE, stdin)){
char *p = strchr(buffer_b, '\n');
if (p){
*p = '\0';
}
}
int len_a = strlen(buffer_a);
int len_b = strlen(buffer_b);
int len_both = (len_a + len_b);
printf("First string: %s", buffer_a);
printf("Length of first string: %i\n", len_a);
printf("Second string: %s", buffer_b);
printf("Length of second string: %i\n", len_b);
if(len_both < 70){
concat = strcat(buffer_a,buffer_b);
printf("Concatenated string: %s\n", concat);
} else{
printf("Length of combined strings > 70\n");
}
return 0;
}
关于C 中的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20291096/