ASCII 和字符程序
ASCII and char programs
#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。
相关文章:
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- C++ 电话号码字母拨号程序 - 语法错别字?还是非 ASCII 字符?
- 有人可以在下面的示例 C++ 程序中解释字符数组 KCHAR1 的奇怪行为吗?
- c ++控制台应用程序,如何在控制台外部打印字符
- 为 Sql 服务器实现 odbc 包装器.将数据库数据读取为字符或要求驱动程序将数据转换为 C 类型
- C++ |为什么执行此程序后我会得到奇怪的字符?
- C ++程序在字符数组中插入单词
- C++从句子中删除给定字符的程序不起作用
- 程序,它接受用户输入的字符并按出现的降序显示它们
- 找不到如何创建使用指针、字符和 for 函数组合的程序
- 编写一个程序,输入整数 n 并打印该数字的字符数(符号除外)
- 程序输出奇怪的字符
- C++程序,将整数输入转换为字符的问题
- 将 C 程序转换为具有大量字符* 和无符号字符转换错误的C++
- 使用独立的 c++ 程序处理用 C 编写的字符设备驱动程序
- Visual C 32位整数从文件到8位字符到文件 - 程序在某些整数上崩溃
- C 程序仅在字符阵列获得“ 1000!”的输入时才在DELETE上崩溃
- 当我们在以下程序(C )中输入字符时,该如何解决
- ASCII 和字符程序
- 我的 c++ 程序中的字符数组不会打印任何内容