-5

に関数値を返したいmain()。これが私のコードです:

#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>
#include <fstream>

using namespace std;

void Cryp(char *str){
    int len = strlen(str);
    int ch;
    for(int i=0;i<len;i++){
        ch = str[i];
        ch = ~ch;
        str[i]=ch;
    }
}

char Deco(char *DESTINATION){

  string line,str;
  ifstream myfile(DESTINATION);

  if (myfile.is_open()) 
  {
    while (getline (myfile,line))
    {
      string str(line); 
      str.erase (str.begin()+0, str.end()-9);
      cout<<str; // THIS HAS TO BE RETURNED TO main()!-BUT HOW ??
    }
    myfile.close();
    //remove(DESTINATION);
  }

  else cout << "Unable to open file";

  return str.c_str();  
}

int Dec(char *SOURCE, char *DESTINATION){
    char Byte;

    FILE *inFile = fopen(SOURCE,"rb");
    FILE *outFile = fopen(DESTINATION,"wb");

    if(inFile==NULL||outFile==NULL){
        if(inFile) fclose(inFile);
        if(outFile) fclose(outFile);
        return 1;
    }
    else{
        while(!feof(inFile)){
            Byte = (char)fgetc(inFile);
            char newString[256];
            sprintf(newString, "%c", Byte);
            Cryp(newString);
            fputs(newString, outFile);
        }
        fclose(inFile);
        Deco(DESTINATION);
    } 

    return 0;
}

main()
{
    Dec("/home/highlander/NetBeansProjects/simple/dist/Debug/GNU-Linux-x86/text.dat","/home/highlander/NetBeansProjects/simple/dist/Debug/GNU-Linux-x86/text_instant.dat");
    cout<< Deco(char);
}

str関数内の値char Deco(char *DESTINATION)をに渡す方法main()

4

3 に答える 3

2

を返すだけstd::stringです:

std::string Deco(char *DESTINATION){

   // rest of code here

   return str;
}

intまた、リターン指定子が欠落しており、意味がmainありDeco(char)ません。

また、次の行を変更してください。

string str(line); 

str = line;
于 2013-09-05T10:48:16.963 に答える
1

ローカル変数へのポインタを返しています。これは、呼び出し元にダングリング ポインターを与え、未定義の動作です。それに加えて、戻り値の型はあなたが返すものと一致しません。

を返すことで、トラブルを回避できますstd::string

std::string Deco(const char *DESTINATION)
{
 ....
 return str;
}

int main()
{
  std::cout << Deco("Hello") << std::endl;
}
于 2013-09-05T10:48:27.073 に答える