c++中的字符到整数转换
Char to Integer coversion in c++
我正试图在我的c++程序中将Char转换为Int,遵循了这个网站上的一些答案,但仍然不起作用。我有一个输入文件,文件ld.txt 中有以下数据
4
8 2
5 6
8 2
2 3
>/LD<ld.txt
int main()
{
using namespace std;
std::vector<int> nums;
int i,k;
char j;
for(i=0;;i++)
{
j=fgetc(stdin);
int l =j - 48;
if(feof(stdin))
break;
nums.push_back(l);
cout<<nums[i]<<endl;
}
}
输出为:
4
-38
8
-16
2
-38
5
-16
6
-38
8
-16
2
-38
2
-16
3
-38
不确定为什么我得到负数
输出中的负数表示输入文件中值小于48的字符。具体地,空格(' '
或32)和换行符('n'
或10)各自小于48。
以下是从文件中读取整数列表的其他方法:
// UNTESTED
int main () {
int i;
std::vector<int> results;
while ( std::cin >> i )
results.push_back(i);
}
或
// UNTESTED
int main () {
std::vector<int> results;
std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
std::back_inserter(results));
}
或者这个
// Thanks, WhozCraig
int main () {
std::vector<int> results((std::istream_iterator<int>(std::cin)),
std::istream_iterator<int>());
}
这应该是您正在寻找的
int main() {
vector<int> nums;
int i,k;
char j;
while(cin >> j){
int l =j - 48;
nums.push_back(l);
}
for(int i =0; i < nums.size(); i++)
cout << nums[i] << " ";
cout << endl;
}
问题是,cin忽略了空白和换行符。我以前从未使用过fgetsc,但我猜它不会忽略空白/换行
-38 = 10 - 48
,即-38 = 'n' - '0'
在C(以及C++)中,可以将字符文字用作整数。
您可以跳过测试值的无效字符读取:
#include <cctype>
if (isdigit(j)) ...
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 如何在C++中将整数转换为其数字数组
- 如果整数与指针大小相同,则重新解释将整数转换为指针双射是否具有双射作用?
- 将最小值整数转换为无符号长整型
- 为什么我们不能将使用异或运算找到的整数转换为字符?
- 在C++中,将无符号整数转换为八进制表示,反之亦然的最佳方法是什么
- 将74位整数转换为以31为底的整数
- 独立于实现的浮点/整数转换
- 以最少的步骤将给定整数转换为另一个整数
- 浮点到整数转换出错(即使浮点数已经是整数)
- 了解双精度转换与整数转换中的整数与截断关系
- 禁止具有精度损失的整数转换
- 将任意整数转换为 void*
- 将 32 位大端有符号整数转换为有符号小端整数
- char a[0] 使用 itoa() 将整数转换为字符串的目的
- 使用函数时从整数转换为字符串
- 尝试从整数转换为字符串的月份
- 如何在C++中将整数转换为字节,以便 Unity 在通过 UDP 传输后能够理解它们
- 如何将 Q 格式的整数转换为浮点数(反之亦然)
- 如何避免字符串到整数转换情况下的无效参数异常