majinvegeta010688
majinvegeta010688

Reputation: 1

Converting a Constant Char to a char C++

Here is the beginning of my program that makes long strings of 10. Every time I try to set bigfor to "0" it says it needs to be converted from a constant char to a char. How is this done?

// basic file operations
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

int main () {



char bigfor[10];
int arrayvar = 0;
int a;
int b;
int c;
int d;
int e;
int f;
int g;
int h;
int i;
int j;

// Constants

int variable1 = 0;
int variable2 = 1;
int variable3 = 2;
int variable4 = 3;
int variable5 = 4;
int variable6 = 5;
int variable7 = 6;
int variable8 = 7;
int variable9 = 8;
int variable10 = 9;






for (a=0; a < 36; a++)

{

switch (a)

 {
case 0:
  bigfor[variable1] = "0";
   break;
 case 1:
  bigfor[variable1] = "1";
   break;
 case 2:
  bigfor[variable1] = "2";
   break;
 case 3:
  bigfor[variable1] = "3";
   break;
 case 4:
  bigfor[variable1] = "4";
   break;
 case 5:
  bigfor[variable1] = "5";
   break;
 case 6:
  bigfor[variable1] = "6";
   break;
 case 7:
  bigfor[variable1] = "7";
   break;
 case 8:
  bigfor[variable1] = "8";
   break;
 case 9:
  bigfor[variable1] = "9";
   break;
}


 ofstream myfile;
  myfile.open ("codes.txt");
  myfile << bigfor[variable1];
  myfile << bigfor[variable2];
  myfile << bigfor[variable3];
  myfile << bigfor[variable4];
  myfile << bigfor[variable5];
  myfile << bigfor[variable6];
  myfile << bigfor[variable7];
  myfile << bigfor[variable8];
  myfile << bigfor[variable9];
  myfile << bigfor[variable10];
  myfile << '\n';
  myfile.close();


}
 return 0;
}

Upvotes: 0

Views: 199

Answers (3)

You need to fill the characters but you are filling a literal String.Try this way

bigfor[variable1] = '0'

Upvotes: 0

user4815162342
user4815162342

Reputation: 155216

You are misreading the error. What it tells you is that it cannot convert const char * (pointer to const char, i.e. a C string) to char (a single character).

A literal such as "0" represents a zero-terminated constant array of characters and, when used in an expression, converts to a pointer to the first character in the array. What you want is a single character, which is represented by single quotes: '0' instead of "0".

Upvotes: 3

bigfor is an array of type char, but you're putting strings into it.

Text between double quotes, such as "0" are interpreted by the compiler to be literal strings.

Text between single quotes such as '0' are interpreted by the compiler to be literal chars.

So when you add chars to bigfor, you should use single quotes to tell the compiler that they are chars, instead of strings.

bigfor[variable1] = '0';

Upvotes: 4

Related Questions