[英]Function that stores string including tabs,spaces and new lines in C
I wanted to store a string up to n characters including tabs,spaces and new line chars but i can't understand how to get this '\0'
char only at the end of the string.我想存储一个最多 n 个字符的字符串,包括制表符、空格和换行符,但我不明白如何仅在字符串末尾获取这个
'\0'
字符。
void takeString(char *c,int n)
{
int i=0;
char *result = fgets(c,n,stdin);
if(result)
{
while(c[i] != '\0')
i++;
if(c[i]=='\0')
c[i] = ' ';
}
c[n] = '\0';
}
but i can't understand how to get this '\0' char only at the end of the string.
但我无法理解如何仅在字符串末尾获取此 '\0' 字符。
if(c[i]=='\0') c[i] = ' ';
causes c[]
to no longer be a string as it lacks a null character .导致
c[]
不再是字符串,因为它缺少null 字符。
c[n] = '\0';
has 2 problems.有2个问题。 It does not make
c[]
a string again as it is not setting the character after the ' '
and 2) it is likely setting a character outside the array pointer to my c
resulting in undefined behavior (UB).它不会再次使
c[]
成为字符串,因为它没有在' '
和 2 之后设置字符,并且可能会在指向我的c
的数组指针之外设置一个字符,从而导致未定义的行为(UB)。
Instead, after c[i] = ' '
, set the next character to '\0'
.相反,在
c[i] = ' '
之后,将下一个字符设置为'\0'
。
It remains unclear why OP wants to append a space character.目前尚不清楚为什么 OP 想要 append 一个空格字符。
void takeString(char *c, int n) {
int i=0;
//char *result = fgets(c,n,stdin);
char *result = fgets(c,n-1,stdin); // Leave room to append a ' '
if(result) {
while(c[i] != '\0') {
i++;
}
//if(c[i]=='\0')
c[i++] = ' ';
c[i] = '\0';
}
// c[n] = '\0';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.