user344336 user344336 -4 years ago 66
C++ Question

invalid operands of types ‘int(const char*)’ and ‘const char [11]’ to binary ‘operator<<’ while trying to write backup program (C++)

Please before you awnser this more than likely obvious question keep in mind that I am a sort of pleb programmer still trying to learn C++... If there are any obvious mistakes go easy on me.

So I am attempting to program a program that will create a backup of whatever file/directory the operator would like, but I keep getting a odd error. I have tried to use + instead of << (I know rookie move but you never know). I have also tried setting a std::sting but got a similar error (I have tried almost anything, but of course not everything because I havent fixed it yet).

Here is the code:

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std ;
int main()
{
char name ;
char named ;
std::cout << "This program will create a backup of whatever directory you would like. Please enter what you would like the backup to be named: "
std::cin >> name ;
std::cout << "Now please enter what directory you wold like to be backed up (Example: /bin/bash): " ;
std::cin >> named ;
system << "tar -zcvf " << name << "tar.gz " << named ;
return 0 ;
}


And this is the error I keep receiving:

backup.cpp: In function ‘int main()’:
backup.cpp:12:12: error: invalid operands of types ‘int(const char*)’ and ‘const char [11]’ to binary ‘operator<<’
system << "tar -zcvf " << name << "tar.gz " << named ;


(I know I should add breaks but at this point I am way past over it {for now})

Thank you to all who awnsered.. Very simple mistake and fix but I find this the best way to learn.

Answer Source

You have multiple problems in your program.

  • Missing ; in one of the lines.
  • You need to use std::getline to read strings.
  • Your name and named variables should be strings not characters.
  • std::system is a function that takes a command line string argument.

For example:

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

int main()
{
    string name;
    string named;
    std::cout << "This program will create a backup of whatever directory you would like."
        "Please enter what you would like the backup to be named: ";
    std::getline(cin, name);
    std::cout << "Now please enter what directory you wold like to be backed up"
        " (Example: /bin/bash): ";
    std::getline(cin, named);
    std::system(("tar -zcvf " + name + "tar.gz " + named).c_str());
    return 0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download