ASCII 和字符程序

ASCII and char programs

本文关键字:程序 字符 ASCII      更新时间:2023-10-16
#include <iostream>
#include <string>
using namespace std;
int main()
{
string c;
cout << "Enter a character: ";
cin >> c;
cout << "ASCII Value of " << c << " is " << int(c);
return 0;
}

这段代码有什么问题?

name error : ||=== Build: Debug in gfghf (compiler: GNU GCC Compiler) ===|
C:UsersahmedDesktopgfghfmain.cpp||In function 'int main()':|
C:UsersahmedDesktopgfghfmain.cpp|10|error: invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'int'|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|

只需将string c;替换为char c;,因为您只想打印 ASCII 值。 将c作为string类型没有任何意义。

int main() {
   char c;
   cout << "Enter a character: ";
   cin >> c;
   cout << "ASCII Value of " << c << " is " << int(c);
   return 0;
}

在不修改您使用的数据类型的情况下,您也可以尝试一下

#include <iostream>
#include <string>
using namespace std;
int main()
{
string c;
cout << "Enter a character: ";
cin >> c;
cout << "ASCII Value of " << c << " is " << int(c[0]);
return 0;
system("PAUSE");
}

====

======================================================================

它不接受int(c(的原因是它是字符串类型,而字符串是字符的集合

int(c[0](//告诉编译器我们正在查看一个字符,而不是 到字符串

这段代码有什么问题?

它显然是用来读取单个字符,但读取的是整个字符串,并且字符串不能通过简单的强制转换转换为整数。

快速修复:

char c;
cout << "Enter a character: ";
cin >> c;

更可靠的解决方案是读取整个输入字符串,然后检查用户是否实际上只输入了一个字符,然后使用该单个字符:

#include <iostream>
#include <string>
int main()
{
    std::string line;
    std::cout << "Enter a character: ";
    std::getline(std::cin, line);
    if (line.size() == 1)
    {
        std::cout << "ASCII Value of " << line[0] << " is " << static_cast<int>(line[0]) << 'n';
    }
    else
    {
        std::cout << "Enter a single character!n";
    }
}

另请注意,C++不能保证 ASCII,尽管在您的计算机上可能是 ASCII。