我写了一个程序来解决这个问题。 "编写一个程序,给定一个字符串、一个宽度和一个空字符串用于输出,将字符串置于输出区域的中心。使用一个函数,如果格式化成功则返回 1,如果有任何错误则返回 0,例如字符串更大然后长度”。我的问题是我的程序在打印字符串时只返回了很多奇怪的字符。而且它不会标记为 0。我可以做些什么来修复我的代码或更好地解决问题?
完整代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int formatString(char str[250], char strcopy[250], int width);
int main()
{
char str[250];
char strcopy[250];
int width;
int outcome;
printf("Enter some text:\n");
gets(str);
printf("\nEnter a width (to check): ");
scanf("%d", &width);
printf("What you entered:");
printf("| %s |\n", str);
printf("\n");
outcome = formatString(str, strcopy, width);
if (outcome = 1)
{
printf("String copied.\n");
printf("| %s |", strcopy);
}
else
{
printf("Use a width val. that is the length of string\n");
}
return 0;
}
int formatString(char str[250], char strcopy[250], int width)
{
int sapceCheck;
int temp = 0;
sapceCheck = width - 1;
for (int i = 0; i < width; i++)
{
if (str[i] == '\0')
{
printf("Formating sucessful\n");
strncpy(str, strcopy, sizeof(str)-1); * (str + (sizeof(str) - 1)) = '\0';
temp = 1;
}
}
if (temp == 0)
{
return 0;
}
else
{
printf("Formating not sucessful\n");
printf("Width does not work\n");
return 0;
}
}
最佳答案
不要错过“Soravux”发布的答案,其中包含有关如何修复“问题”代码的所有正确建议。
这是另一种方法。但是,调用者必须确保目标字符串“strcpy”足够大(长度+1)以容纳输出:
int formatString(char *str, char *strcopy, int length)
{
size_t strLength;
strLength = strlen(str);
/* Check if the string is greater than the length */
if(strLength > length)
return(0);
/* Print the centered 'str' to 'strcopy'. */
sprintf(strcopy, "%*s%*s",
(length+strLength) / 2, str, //leading spaces & 'str'
length - ((length+strLength) / 2), "" //trailing spaces
);
return(1);
}
关于C 字符串格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23508244/