【问题标题】:C++: Getting random negative values when converting char to intC ++:将char转换为int时获取随机负值
【发布时间】:2016-11-14 05:02:39
【问题描述】:

当我尝试将字符从从文件读取的字符串转换为 int 时,为什么会得到负值?

fin.getline(text, 512);
fin.close();
someInt = (int)text[0]; // It happens to be the random value and always negative.

完整代码:

问题本身在于解密函数。 当我从文件中读取字符串并将字符从该字符串转换为 int 时,我得到负值,总是随机的,即使字符相同。

// WUEncryptor.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

void Encrypt(string filePath, string password = "");
void Decrypt(string filePath, string password = "");

int main(int argc, char** argv)
{
    int mode = 0;
    string filePath;

    if (argc > 2) {
        mode = atoi(argv[1]);
        filePath = argv[2];

        /** Checking which mode to use */
        switch (mode) {
        case 0:
            if (argc > 3)
                Encrypt(filePath, argv[3]);
            else
                Encrypt(filePath);
            break;

        case 1:
            if (argc > 3)
                Decrypt(filePath, argv[2]);
            else
                Decrypt(filePath);
            break;
        default:
            return 0;
        }
    }
    else {
        /** If something was entered wrong by user, print the error message and quit */
        cout << "Invalid launch..\nYou should use arguments\nFor example: \"WUEncryptor 0 EncryptedFile\n";
    }
    return 0;
}

    /** Encrypting function */
    void Encrypt(string filePath, string password) {
        string text;
        string pass = password;

        /** Quit if pass word isn't determined */
        if (pass == "") {
            cout << "Use \"WUEncryptor 0/1 \"filepath\" password\n";
            return;
        }

        cout << "Enter the message which is going to be encrypted\n";
        char tempstr[512];
        gets_s(tempstr);
        text = tempstr;
        /** Loop that replaces characters in the text */
        for (int i = 0, m = 0, temp = 0; i < text.length(); i++) {

            temp = (int)text[i] + (int)pass[m];
            cout << temp;
            if (temp > 255)
                temp -= 256;
            cout << temp;
            text[i] = (char)temp;

            /** Looping the pass code */
            if (m >= pass.length() - 1)
                m = 0;
            else
                m++;
            cout << "Encrypting " << i << " of " << text.length() << "...\n";
        }
        cout << "Successfully encrypted\nTEXT: " << text << '\n';

        ofstream fout;
        try {
            filePath += ".encrypted";
            cout << "Creating the file...\n";
            fout.open(filePath, ios_base::trunc);
            cout << "Writing to file...\n";
            fout << text;
            fout.close();
            cout << "We're all set!\n";
            system("pause");
        }
        catch (exception) {
            cout << "Something went wrong";
        }
    }

    /** Decrypting function */
    void Decrypt(string filePath, string password) {
        string text, pass;
        pass = password;
        ifstream fin;

        /** Quit if pass word isn't determined */
        if (pass == "") {
            cout << "Use \"WUEncryptor 0/1 \"filepath\" password\n";
            return;
        }
        string openPath = filePath + ".encrypted";

        char tempstr[512];
        try {
            fin.open(openPath);
            fin.getline(&tempstr[0], 512);
            fin.close();
            text = tempstr;
            //cout << (int)text[1];

            for (int i = 0, m = 0, temp = 0; i < text.length(); i++) {

                temp = (int)text[i] - (int)pass[m];
                cout << temp;
                if (temp < 0) 
                    temp += 256;
                cout << temp;
                text[i] = (char)temp;

                /** Looping the pass code */
                if (m >= pass.length() - 1)
                    m = 0;
                else
                    m++;
                cout << "Decrypting " << i << " of " << text.length() << "...\n";
            }
            cout << "Successfully decrypted\nTEXT: " << text << '\n';

        }
        catch (exception) {}

        ofstream fout;
        try {
            string savePath = filePath + ".txt";
            cout << "Creating the file...\n";
            fout.open(savePath, ios_base::trunc);
            cout << "Writing to file...\n";
            fout << text;
            fout.close();
            cout << "We're all set!\n";
            system("pause");
        }
        catch (exception) {
            cout << "Something went wrong";
        }

    }

某人,让我清醒一下:D

【问题讨论】:

  • 你们为什么要投反对票?你甚至不解释
  • text的类型是什么,里面存储的值是什么,someInt的类型是什么,得到的值是什么?
  • 试试 fout.getline(&text[0], 512);或 std::getline (fout, text); en.cppreference.com/w/cpp/io/basic_istream/getline
  • 您的问题被否决的原因是它没有包含足够的信息来给出有意义的答案。
  • @BeLuckyDaf 命名你从fout 读取的文件对我来说似乎很奇怪。

标签: c++ string int fstream


【解决方案1】:

您可能正在使用char* 作为text 的数据类型。 请注意,char 已签名,因此如果您(认为您)的值为例如200 那里,真的是-72,所以如果你把它转换成int,你会得到-72 :)

【讨论】:

  • 我将string 用于text
  • @BeLuckyDaf std::string operator[] 运算符返回一个char,它是有符号还是无符号的实现定义。它显然已在您的系统上签名。
  • @BeLuckyDaf -- 不要进入那个兔子洞。这个答案只是一个猜测。在你提供编译、运行和显示问题的真实代码之前,没有人能告诉你发生了什么。
  • @PeteBecker 现在检查一下,请 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
  • 2015-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-19
相关资源
最近更新 更多