c++中的字符到整数转换

Char to Integer coversion in c++

本文关键字:整数 转换 字符 c++      更新时间:2023-10-16

我正试图在我的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)) ...