我有这段代码:
int main(){
char buf[40];
char buff[40];
char bufff[40];
fgets(buf, 40, stdin);
fgets(buff, 40, stdin);
fgets(bufff, 40, stdin);
}
输入:
Hello
from
Earth
我必须有这个输出:
Hello
from
Earth
Hello from Earth
我将代码发送到一个vutation平台,它返回给我,使用以下代码我会得到错误的输出:
buf[strlen(buf)-1] = "";
buff[strlen(buff)-1] = "";
bufff[strlen(bufff)-1] = "";
printf("%s\n%s\n%s\n", buf, buff, bufff);
printf("%s %s %s", buf, buff, bufff);
答案 0 :(得分:2)
""
是一个字符串文字,它是一个数组,它将以实现定义的方式转换为整数。您应该使用'\0'
作为NUL字符。试试这个:
#include <stdio.h>
#include <string.h>
int main(void){
/* initialize to avoid undefined behavior when no data is read */
char buf[40] = "";
char buff[40] = "";
char bufff[40] = "";
char *lf;
/* read the input */
fgets(buf, 40, stdin);
fgets(buff, 40, stdin);
fgets(bufff, 40, stdin);
/* remove newline characters if they exists */
if ((lf = strchr(buf, '\n')) != NULL) *lf = '\0';
if ((lf = strchr(buff, '\n')) != NULL) *lf = '\0';
if ((lf = strchr(bufff, '\n')) != NULL) *lf = '\0';
/* remove space characters: implement here to match the actual specification */
if ((lf = strchr(buf, ' ')) != NULL) *lf = '\0';
if ((lf = strchr(buff, ' ')) != NULL) *lf = '\0';
if ((lf = strchr(bufff, ' ')) != NULL) *lf = '\0';
/* print */
printf("%s\n%s\n%s\n", buf, buff, bufff);
printf("%s %s %s", buf, buff, bufff);
return 0;
}
在此代码中省略,您应该检查读数是否成功。
答案 1 :(得分:0)
我创建了这个简单的函数来删除一般的尾随空格。还应该删除额外的空格。您甚至可以轻松地调整它以过滤掉您想要的其他符号。
#define IS_WHITESPACE(Char) (Char == ' ' || Char == '\n' || Char == '\t')
void trim_right(char *string)
{
int i;
for (i = strlen(string) - 1; i >= 0; i++)
if (IS_WHITESPACE(string[i]))
string[i] = '\0';
else
break;
}