簡體   English   中英

不能在 C 中將 sscanf() 用於 char 數組

[英]can't use sscanf() in C for char array

我試圖獲得一個非常大的數字(超過unsigned long long int )。 因此,我將其作為字符串獲取,然后將其逐位轉換為 integer 並使用它。

#include <stdio.h>
#include <string.h>

int main() 
{ 
    char m[100];
    int x;
    scanf("%s",m);
    for(int i=0; i<strlen(m); i++){
        sscanf(m[i],"%d",&x);
        printf("%d",x);
    }

    return 0; 
}

但是,在編譯期間它顯示:

警告:傳遞 'sscanf' 的參數 1 使指針來自 integer 沒有強制轉換

注意:預期為“const char * restrict”,但參數為“char”類型

而且,當我運行程序時,它會給我Segmentation fault (core dumped)錯誤。

我還嘗試了更簡單的代碼來查找問題:

#include <stdio.h>
#include <string.h>

int main() 
{ 
    char m[5];
    char n;
    int x;
    scanf("%s",m);
    n = m[1];
    sscanf(n,"%d",&x);  
    return 0; 
}

但沒有任何改變。

scanf不適用於characters 一旦你有了字符,只需通過減去'0'作為字符將數字轉換為整數:

for(int i=0; i<strlen(m); i++){
    x = m[i] - '0';   // line to change
    printf("%d",x);
}

此外,只是為了確保緩沖區不會溢出,100 字節是好的,但您可能希望在scanf中使用相應的限制並檢查返回碼:

if (scanf("%99s",m) == 1) {

使用sscanf將字符串的單個數字轉換為 integer 是錯誤的方法。 為此,您只需從該數字中減去字符'0'表示的(整數)值。 像這樣:

#include <stdio.h>
#include <string.h>

int main()
{
    char m[50]; // As pointed out, a 4-digit number isn't really very long, so let's make it bigger
    int x;
    scanf("%49s", m); // Limit the input to the length of the buffer!
    for (size_t i = 0; i < strlen(m); i++) { // The "strlen" function return "size_t"
        x = m[i] - '0'; // The characters `0` thru `9` are GUARANTEED to be sequential!
        printf("%d", x);
    }
    return 0;
}

scanf不適用於characters 一旦你有了字符,只需通過減去'0'作為字符將數字轉換為整數:

for(int i = 0; i < strlen(m); i++) {
    x = m[i] - '0';  
    printf("%d", x);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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