ASCII和char程序

时间:2018-03-24 13:54:39

标签: c++

#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:\Users\ahmed\Desktop\gfghf\main.cpp||In function 'int main()':|
C:\Users\ahmed\Desktop\gfghf\main.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)) ===|

3 个答案:

答案 0 :(得分:1)

只需将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;
}

答案 1 :(得分:1)

如果不修改数据类型,您可以尝试使用

#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])//告诉编译器我们正在查看相反的字符                                                                 字符串

答案 2 :(得分: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。