C 用换行符替换空格
我正在尝试为Ti-89计算器制作一个带有换行符的空格,这样我就可以打印行,而不会因为水平字符长度而被剪切。他们通常看起来是这样的C 用换行符替换空格,c,C,我正在尝试为Ti-89计算器制作一个带有换行符的空格,这样我就可以打印行,而不会因为水平字符长度而被剪切。他们通常看起来是这样的 This is a pretty long test ing for the Ti89 Calculator This is a pretty long testing for the Ti89 Calculator 我希望他们看起来像这样 This is a pretty long test ing for the Ti89 Calculator Th
This is a pretty long test
ing for the Ti89 Calculator
This is a pretty long
testing for the Ti89
Calculator
我希望他们看起来像这样
This is a pretty long test
ing for the Ti89 Calculator
This is a pretty long
testing for the Ti89
Calculator
我试着用这个代码来做
void _print_line(char* string)
{
int k = strlen(string);
if(k > 26)
{
int n = 0;
int c = 25;
while(n == 0)
{
if(string[c] == 32)
{
n = 1;
}
else
{
c--;
}
if(c <= 0)
{
n = 2;
}
}
if(n == 1)
{
string[c] == '\n';
}
}
printf("%s\n", string);
}
void\u打印行(字符*字符串)
{
int k=strlen(字符串);
如果(k>26)
{
int n=0;
int c=25;
而(n==0)
{
if(字符串[c]==32)
{
n=1;
}
其他的
{
c--;
}
如果(c您没有插入回车符
替换
字符串[c]=='\n';
与
字符串[c]='\n';
正如蒂尔所说,您没有插入回车符。该行
string[c] == '\n';
需要
string[c] = '\n';
区别是一个“等于”符号和两个
原因是“==”是一个条件运算符,其计算结果为true或false,而“=”是赋值运算符,用于为变量设置值。需要对整个字符串进行处理
保留当前输出字符位置的记录,以检查在输出下一个单词时是否超过指定的宽度。
像这样:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define DISP_OUT stdout
#define DISP_WIDTH 26
int disp_one(char ch){
static int pos;
fputc(ch, DISP_OUT);
if(ch == '\n')
pos = 0;
else
++pos;
if(pos == DISP_WIDTH){
fputc('\n', DISP_OUT);
pos = 0;
}
return pos;
}
typedef enum word_break {
KEEP, BREAK
} WORD_BREAK;
void disp(const char *str, WORD_BREAK word_break){
static int pos;
switch(word_break){
case BREAK:
while(*str){
pos = disp_one(*str++);
}
break;
case KEEP:
while(*str){
if(isspace((unsigned char)*str)){
pos = disp_one(*str++);
continue;
}
const char *end = str;//end : word end (find delimiter)
while(*end && !isspace((unsigned char)*end))
++end;
int len = end - str;//length of next output word
if(pos + len >= DISP_WIDTH && len < DISP_WIDTH){
pos = disp_one('\n');
}
while(str < end){
pos = disp_one(*str++);
}
}
break;
}
}
int main(void){
char *text = "This is a pretty long testing for the Ti89 Calculator";
disp(text, BREAK);
disp("\n", BREAK);
disp(text, KEEP);
return 0;
}
#包括
#包括
#包括
#定义显示输出标准输出
#定义显示宽度26
int disp__one(字符通道){
静态int-pos;
fputc(ch,显示输出);
如果(ch='\n')
pos=0;
其他的
++pos;
如果(位置==显示宽度){
fputc('\n',DISP_OUT);
pos=0;
}
返回pos;
}
typedef枚举单词\u中断{
保持,休息
}断字;
void disp(const char*str,WORD\u BREAK WORD\u BREAK){
静态int-pos;
开关(字断开){
案例中断:
while(*str){
pos=disp_one(*str++);
}
打破
案件审理:
while(*str){
if(isspace((无符号字符)*str)){
pos=disp_one(*str++);
继续;
}
const char*end=str;//end:word end(查找分隔符)
while(*end&!isspace((未签名字符)*end))
++结束;
int len=end-str;//下一个输出字的长度
如果(位置+长度>=显示宽度和长度<显示宽度){
pos=disp_one('\n');
}
while(str
这不是你的问题,但为了可读性(和可移植性),请将if(string[c]==32)
更改为if(string[c]='')
.OT:strlen()
返回size\u t
,而不是int
。