簡體   English   中英

Function 存儲字符串,包括 C 中的制表符、空格和換行符

[英]Function that stores string including tabs,spaces and new lines in C

我想存儲一個最多 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';
}

但我無法理解如何僅在字符串末尾獲取此 '\0' 字符。

if(c[i]=='\0') c[i] = ' '; 導致c[]不再是字符串,因為它缺少null 字符

c[n] = '\0'; 有2個問題。 它不會再次使c[]成為字符串,因為它沒有在' '和 2 之后設置字符,並且可能會在指向我的c的數組指針之外設置一個字符,從而導致未定義的行為(UB)。

相反,在c[i] = ' '之后,將下一個字符設置為'\0'

目前尚不清楚為什么 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM