将字符转换为 int 会显示不相等的数字



我正在尝试将char转换为int以用于for循环,但我得到了我发现的意外结果。

我添加了一个cout行以查看char转换为的值。

char取自一个ifstream,该从包含字母和数字的.txt文件中流式传输。文件中的第一个数字是 3,但它正在转换为 51。

程序代码现在如下

is_number(char)如果char == '0' || char == '1' || char == '2' || ...etc,则返回 true(最多 char == '9' 个(

inifstreamoutofstream

我尝试过石膏转换,例如 int t = (int)inputBint t = static_cast<int>(inputB) ,但它们给出的结果相同。

我犯了菜鸟错误吗?有什么想法吗?

编辑:

极简程序:

#include <fstream>
#include <iostream>
using namespace std;
bool is_number(char);
int main(){
    ifstream in;
    ofstream out;
    in.open("in.txt");
    if (in.fail()){
        return 0;
    }
    out.open("out.txt");
    if (out.fail()){
        return 0;
    }
    char inputA, inputB;
    while (!in.eof()) {
        if (inputA != 'ÿ' && inputA != '') {
            if (is_number(inputB) && inputA != '\'){
                int t = inputB;   //inputB is 3, but t becomes 51
                cout << inputB << " " << t << ".n";
                for (int i = 0; i < t; i++){
                    out << inputA ;
                }
            }
        }
        inputA = inputB;
        in.get(inputB);
    }
    return 0;
}
bool is_number(char c){
    if (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' ||
        c == '6' || c == '7' || c == '8' || c == '9') return true;
    return false;
}

.txt文件"in.txt"的内容是:

zo3logists 10as2ist stewardes2es.3

(我之前加密了一行,后来变成了那个(

int t = inputB;

这不是进行转换的正确方法。这样你就会得到一个字符代码,这不是你想要的。

使用这个:

int t = inputB - '0';

您也可以将其编写为 int t = inputB - 48 ,这是完全相同的(如果您的系统使用 ASCII 编码 - 几乎普遍正确(,但带有 '0' 的版本被认为更具可读性(并且无论字符编码如何都是正确的(。

首先,您的inputAinputB在循环开始时未定义。anatolyg的解决方案是最简单的。你也可以使用这样的东西:

// include <string>
string str;
sstr = inputB;
int t = stoi(str); // you have to be sure that inputB is a number
                   // or need exception handling

当字符集被更改为"1"不在"0"之后时,您将是安全的。但这;)

顺便说一句:你可以简化你的ìs_number(char c)

if ('0' >= c && c <= '9')
    return true
else
    return false

最新更新