簡體   English   中英

在C / C ++中打印所有ASCII值

[英]Printing all the ASCII Values in C/C++

大家好,我與C / C ++語言沒有聯系,只是再次修改了概念,因此遇到了這個問題,我想寫一個程序來顯示所有ASCII字符,所以我寫了以下內容,但是它沒有給出預期的結果。 誰能告訴我這段代碼是什么問題。

#include<iostrem.h>
int main()
{
    unsigned char a;
    for(a = 0; a < 256; ++a)
    {
        cout << a << " ";
    }
    return 0;
} 

a 始終小於256,因為無符號字符不能超過255。您已編寫了無限循環。

您的include也有一個拼寫錯誤和額外的.h並且您沒有在cout上使用std名稱空間。

編輯:最后,從技術上講,ASCII僅計算前128個字符,除此之外的所有內容都是各種擴展字符集的域。

如果可以使用<stdio.h> ,那么會更容易。

#include <stdio.h>

int main()
{
    for(int i = 0; i <= 255; i++) {
      fprintf(stdout, "[%d]: %c\n", i, i);
    }

  return 0;
}

其他答案對此進行了詳細介紹。 我以為我會拋出這樣的疑問,那就是在打印字符之前檢查字符是否可以打印:

#include <cctype>
#include <iostream>

int main()
{
    for(int a = 0; a < 256; ++a) // use int (big enough for 256)
        if(std::isprint(a)) // check if printable
            std::cout << char(a) << " "; // print it as a char
}

試試這個代碼:

=> C ++

#include<iostream>
int main ()
{
    int a;
    for(a=0;a<256;++a)
    {
        cout<<(char)a<<" ";
    }
    return 0;
} 

=> C

#include<stdio.h>
int main ()
{
    int a;
    for(a=0;a<256;++a)
    {
        printf("%c " a);
    }
    return 0;
}

您的代碼有很多問題。

首先,沒有iostrem.h 將其更正為iostream.h g ++將給出一個fatal error: iostream.h: No such file or directory因為標准庫不得包含在.h

將其更改為#include <iostream>導致error: 'cout' was not declared in this scope 您需要std::cout << a才能成功編譯。

但是,即使解決了上述所有問題,gcc仍使用-Wall -Wextra -pedantic選項輸出了一個重要的信息

warning: comparison is always true due to limited range of data type

這是因為256超出了unsigned char的典型范圍。 僅當char具有8位以上的字符時才有效,而您的平台則不是如此。 您應該始終啟用所有編譯器警告。 這將幫助您確定很多問題,而無需在這里詢問。

但是,除非臨時必要,否則不要將類型小於int類型用於臨時值,因為無論如何它們都會在表達式中提升為int

有用。

#include <iostream>
using namespace std;

int main() {
    char a;
    int i;

    for (int i=0; i<256; i++){
        a=i;
        cout << i << " " << a << " " <<endl;
    }
    return 0;
}

這顯然是一個非常老的問題,但是如果有人想實際打印ASCII碼及其對應的數字,請執行以下操作:

#include <iostream>
int main()
{  

char a; 

for (a=0; a<=127; a++)
{
    std::cout<<a<<" ";
    std::cout<<int(a)<<" "<<std::endl;
}

return 0;

}

注意/給讀者:

代碼0-31:無法打印的字符; 用於格式化和控制打印機

代碼32-127:可打印字符; 代表字母,數字和標點符號。

#include <stdio.h>
int main ()
{
    unsigned char a;
    for(a=0;a<=255;a++)
    {
        printf(" %c  %d  \n ",a,a);
    }
    getch();
    return 0;
}

你得到什么結果? 我認為你需要輸出

Cout<<(chat)a;

否則,它只會返回它分配的整數

暫無
暫無

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

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