Joe
Joe

Reputation: 104

C++ Error: 'Input string was not in a correct format'

I get the error:'Input string was not in a correct format'

This code, when I use it in C#, works fine, but I translated it myself, so there could be an error there. (I normally use this for text encryption, as it is short and quick)

This is my C++ code:

void encrypt()
{
    string psw = "mystring";
    System::String^ encr;
    int tot;
    int num;
    int lng = psw.size();
    char pswchar[1024];
    strcpy_s(pswchar, psw.c_str());
    System::String^ istr;
    for (int i = 0; i < lng; i++)
    {
        {
            ostringstream ss;
            ss << pswchar[i];
            istr = gcnew System::String(ss.str().c_str());
        }
        num = int::Parse(istr) + 15; // << I get the error here
        tot += num;
    }
    ostringstream convert;
    convert << tot;
    encr = gcnew  System::String(convert.str().c_str());
    File::WriteAllText("C:\myfolder\mypath.txt", encr);
}

This is my C# Code:

void encrypt()
{
    string psw = "mystring";
    string encr;
    char[] pswchar = psw.ToCharArray();
    for (int i = 0; i < pswchar.Length; i++)
    {
        int num = Convert.ToInt32(pswchar[i]) + 15;
        string cvrt = Convert.ToChar(num).ToString();
        encr += cvrt;
    }
}

Upvotes: 1

Views: 1424

Answers (1)

Adam Burry
Adam Burry

Reputation: 1902

I think this is what you asked for... but it is a bit crazy:

#include <string>

using namespace System;

std::string encrypt(const std::string& s) {
  std::string r(s);
  for (int i = 0; i < r.size() ; ++i) {
    r[i] += 15; // !!!
  }
  return r;
}

int main(array<System::String ^> ^args)
{
    std::string s = "Hello World";
    System::String^ ss = gcnew String(encrypt(s).c_str());
    Console::WriteLine(ss);
    return 0;
}

Output:

Wt{{~/f~?{s

Upvotes: 2

Related Questions