EDIT: I also got an answer to make sector a vector of vectors:
vector<vector<char>>sector;
and that gets rid of the rest of my errors.
EDIT: I've made sector an array of pointers as someone suggested, and still get three errors:
EDIT: I have edited the program, but it has not fixed all of the errors:
I have this section of a program:
char* load_data(int begin_point,int num_characters);
ifstream mapdata("map_data.txt");
const int maxx=atoi(load_data(0,2));
const int maxy=atoi(load_data(2,2));
char** sector=new char[maxx][maxy];
char* load_data(int begin_point,int num_characters)
{
seekg(begin_point);
char* return_val=new char[num_characters+1];
mapdata.getline(return_val,num_characters);
return return_val;
}
And I get these errors:
line 5>error C2540: non-constant expression as array bound
line 5>error C2440: 'initializing' : cannot convert from 'char (*)[1]' to 'char **'
line 14>error C3861: 'seekg': identifier not found
per seekg: yes I know I have to include fstream, I included that in main.cpp, this is a separate .h file also included in main.cpp.
How do I fix the errors? Specifically, how to I fix the errors while keeping all my variables global?
Also, if it helps, this is map_data.txt:
10
10
00O
99!
1
55X
19
What is a question?
18
This is an answer
1
1
2
1
Well,
function load_data(int,int) returns a char.
You are passing that char to the atoi function, that takes a char*. In addition to that, you are probably not including stdlib.h header file!!
#include <cstdlib>
int atoi(const char*);
If you dont wan't to include stdlib.h, then you could declare atoi as extern, but be aware when you compile this module.
extern int atoi(const char*)
Take into account that the argument of atoi function must be a null-terminated string.
In order for your code to work, you should make function load data return a char*, not a char.
char* load_data(int,int);
So, now you could do
//notice these aren't const, they rely on non-compile time available data.
int maxx = atoi (load_data(....));
int maxy = atoi (load_data(....));
If you are in C++, load_data function could return a std::string.
std::string load_data(int,int)
and then use c_str() method, which returns a C-String from a C++ string.
const char* std::string:c_str()
int maxx = atoi(load_data(....).c_str());
int maxy = atoi(load_data(....).c_str());
In addition to that, you shouldn't
(regarding
line 5>error C2540: non-constant expression as array bound
line 5>error C2440: 'initializing' : cannot convert from 'char (*)[1]' to 'char **'
)
char sector[maxx][maxy];
You should
char** sector = new char[maxx][maxy]();
and dont forget to free this memory
delete[](sector);
You can't return a pointer to a stack variable. And arrays need to be returned as pointer types.
Try:
char* load_data(int begin_point,int num_characters)
{
seekg(begin_point);
char* return_val = new char[num_characters+1];
mapdata.getline(return_val, num_characters);
return return_val;
}
char* foo = load_data(...);
...
delete [] foo;
I'm not quite sure what is the goal of your exercise. But if you want to read 'stuff' from file and get it in format that you expect (like int, strings ...) you can just use operator>> and getline like this:
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream ifs("data.txt");
if (!ifs.is_open()) return 0;
int maxx;
int maxy;
ifs >> maxx >> maxy;
cout << maxx << " " << maxy << endl;
// ----
char OO_0[4]; // can use char[] or string, see next
ifs >> OO_0;
OO_0[sizeof(OO_0)] = 0;
cout << OO_0 << endl;
// ----
string _99;
ifs >> _99;
cout << _99 << endl;
int one;
string _55_X;
int _19;
string what_is;
ifs >> one >> _55_X >> _19 >> ws;
// ws gets rid of white space at the end of the line ...
// this is because getline would only read that ws up to eol
getline(ifs,what_is);
cout << one << " " << _55_X << " " << _19 << " " << what_is << endl;
ifs.close();
}
And you get output like this:
10 12
00O
99!
1 55X 19 What is a question?
Is that what you were after? NOTE: I'm using c++ because I noticed you mentioned "main.cpp"
Related
I was trying to hold the text entered by user inside an Char array but it does not end up well. I tried this method but i think it deleted after c++ 11.
Here's my code :
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char sentence[2];
cout << "Enter your sentences : ";
gets_s(sentence);
cout << sentence << endl;
system("PAUSE");
return 0;
}
It gives overload error and doesnt works.
Chances are you are trying to get the string literal that is longer than 2 characters yet not being able to insert it into your buffer of:
char sentence[2];
Increase the buffer size to something more acceptable:
char sentence[255];
That being said in C++ you should prefer std::string to character array and std::getline to gets_s.
I am creating a time class (string base) for my school project! I get a pointer character for the time!I have a function to normalize the time if it is weird.
in normalize function I have a character array to store the correct time but when I want to Assign the character array to the pointer character it is going false!
char st[10] = "", sh[3] = "", sm[3] = "", ss[3] = "";
itoa(hour, sh, 10);
itoa(minute, sm, 10);
itoa(second, ss, 10);
if(hour<10){strcat(st, "0");}
strcat(st, sh);strcat(st, ":");
if(minute<10){strcat(st, "0");}
strcat(st, sm);strcat(st, ":");
if(second<10){strcat(st, "0");}
strcat(st, ss);strcat(st, "");
stime = st;
stime is pointer character which save the time in class.
when I want to use value of stime I get very weird result. stime get the value of last class stime. for example I have this code:
time a("1:50:0"), b("4:5:10");
a.print();
b.print();
but I get 04:05:10 for two classes and I don't know why!
If you need the rest of code I upload it here: Google Drive link to file
When I compile your code I get the following warning:
warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
time(char *t = "0:0:0"):stime(t){normalize(-1, -1, -1);}
This is what is causing your issue.
"0:0:0" in C++ is a const char[5] which can be converted implicitly to a const char * but not to a simple char *, which is the storage type you have chosen for time.
As others have mentioned, in C++ you should use std::string rather than char*.
As a general rule you should never ignore warnings unless you are sure you know why they are appearing. Often, as in this case, they are telling you that your code is not going to behave in the way you'd expect.
You can try this as a C++ solution:
#include <sstream>
#include <iomanip>
#include <iostream>
using namespace std;
string GetComponent(int value)
{
ostringstream oss;
oss << setfill('0') << setw(2) << value;
return oss.str();
}
void PrintTime(int hh,int mm,int ss)
{
cout << GetComponent(hh) << ':' << GetComponent(mm) << ':' << GetComponent(ss) << endl;
}
Usage example:
PrintTime(1,2,3);
PrintTime(1,2,33);
PrintTime(1,22,33);
PrintTime(11,22,33);
I have a problem in compiling this source .
This is my source :
#include <iostream>
#include <string>
using namespace std;
char pass[7],d;
int v;
int isvalid(char pass);
int main(int argc, char** argv) {
cout<<"Enter Password :";
gets(pass);
cout<<endl;
v=isvalid (pass);
if(v==1){
cout<<"The Password is Correct . You can Come in"<<endl;
}
else{
cout<<"The Password in InCorrect ! You Can't Come In"<<endl;
}
system("PAUSE");
return 0;
}
/*-----------Functions--------------*/
int isvalid(char pass){
d="Pokerface";
if(pass==d){
return 1;
}
else{
return 0;
}
}
It should get a password from user and check it with isvalid function and say It is correct or not but compiler (DEV C++ 5) shows me these errors :
In function 'int main(int, char**)':
14 17 [Error] invalid conversion from 'char*' to 'char' [-fpermissive]
8 5 [Note] initializing argument 1 of 'int isvalid(char)'
In function 'int isvalid(char)':
26 3 [Error] invalid conversion from 'const char*' to 'char' [-fpermissive]
28 recipe for target 'main.o' failed
What is the problem ? please help me.
pass is an array of char ( char * ), and your isvalid funciton take a charas it's first argument. I suspect you want to change your isvalid function so that it takes a char* as an argument, like this :
int isvalid(char* pass){
Also, keep in mind that when you do this :
if (pass==d)
You are NOT comparing the strings, but the pointers. If you want to check that the two string are identical, that's not going to work
For strings comparisons use strcmp(str1, str2) in string.h.
Since you have tagged C++ to this question, I would suggest using std::string
#include <iostream>
#include <string>
using namespace std;
bool isvalid(const std::string & pass);
int main(int argc, char ** argv) {
string pass;
cout << "Enter Password" << endl;
cin >> pass;
if (isvalid(pass))
cout << "The Password is Correct. You can Come in" << endl;
else
cout << "The Password in InCorrect ! You Can't Come In" << endl;
return 0;
}
bool isvalid(const std::string & pass) {
return pass == "Pokerface";
}
int isvalid(char pass)
You probably meant to take in a char* there, but you shouldn't do that either: use std::string instead. Additionally, your function should return a bool instead of an int.
bool isvalid(const std::string& pass)
You should then update pass and d to be std::strings as well and use std::cin instead of gets to read from stdin. There is no reason for pass or d to be global variables, so make them local to your functions.
If you keep your function as taking a char* your comparison will not work, because you will just be comparing the pointers. You would need strncmp for that.
So i have a char *. And i want to cut off some bit at the end. So
char *sentence = "My name is Ted";
How do I cut off the Ted. I could make it a string and then use substring (coming from Java thats my go to method) but id rather not do that way. But im not sure how to do it with a char *.
EDIT: Further on the problem. The issue is in a function that takes a process and is meant to return the location when that process is started from. Thats fine i can get that. But the parameter char *procLocation is passed by reference so the location will be sent back there.
I can only get the location that includes the name of the process. I want to cut off the name of the process and just return the location. Ive tried making the location a string and doing a substring (string - length of the processName). Thats fine. But
procLocation = location.c_str(); // where location.substr is the location - the process name
gives back an error: error C2440: '=' : cannot convert from 'const char *' to 'char *'
Since that is a string literal, you can't modify it.
If you did:
char sentence[] = "My name is Ted";
You could simply set the character before Ted to \0.
You might be better off using std::string though.
Instead of cutting off your literal, you could use std::string constructor that copies fewer characters than is available in your char*:
const char *data = "Hello, Ted!";
string s(data, data+8);
cout << s << endl;
This prints Hello, T
This approach is less wasteful than making a std::string and taking a substring.
To your original problem, as you're coming from Java, you should (should, in the sense of RFC2119) definitely use std::string:
#include <string>
#include <iostream>
using namespace std;
int main(int argc, const char** argv) {
// copy c-string to std::string
string arg0 = argv[0];
cout << arg0 << endl;
// find last occurrence of path separator
size_t found = arg0.find_last_of("/\\");
// split off filename part of string
cout << arg0.substr(0,found) << endl;
return 0;
}
Further, you should not (should not, in the sense of RFC2119) declare the char array as a char pointer, but as a char array:
char[] s0 = "Hello World!"; // <-- is better
char * s1 = "Hello World!"; // <-- avoid this
See this post for actual reasons why this is better. It also gives the reasons for why not to modify such rvalue strings.
You've tagged the question 'c++' and 'string' but you say you don't want to do this with string and substr ? Not sure why that is. You should prefer these over char* and C style string manipulation functions wherever possible.
To do it the C++ way:
string sentence = "My name is Ted";
cout << "\"" << sentence.substr(0, sentence.rfind(' ') ) << "\"" << endl;
Although you could (modifying your code slightly so that you have a mutable string) do this in C:
char sentence[] = "My name is Ted";
*strrchr(sentence, ' ') = '\0';
printf("\"%s\"\n", sentence);
atoi() is giving me this error:
error C2664: 'atoi' : cannot convert parameter 1 from 'char' to 'const char *'
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
from this line:
int pid = atoi( token.at(0) );
where token is a vector
how can i go around this?
token.at(0) is returning a single char, but atoi() is expecting a string (a pointer to a char.) Either convert the single character to a string, or to convert a single digit char into the number it represents you can usually* just do this:
int pid = token.at(0) - '0';
* The exception is when the charset doesn't encode digits 0-9 in order which is extremely rare.
You'll have to create a string:
int pid = atoi(std::string(1, token.at(0)).c_str());
... assuming that token is a std::vector of char, and using std::string's constructor that accepts a single character (and the number of that character that the string will contain, one in this case).
Your example is incomplete, as you don't say the exact type of the vector. I assume it is std::vector<char> (that, perhaps, you filled with each char from a C string).
My solution would be to convert it again on char *, which would give the following code:
void doSomething(const std::vector & token)
{
char c[2] = {token.at(0), 0} ;
int pid = std::atoi(c) ;
}
Note that this is a C-like solution (i.e., quite ugly in C++ code), but it remains efficient.
const char tempChar = token.at(0);
int tempVal = atoi(&tempChar);
stringstream ss;
ss << token.at(0);
int pid = -1;
ss >> pid;
Example:
#include <iostream>
#include <sstream>
#include <vector>
int main()
{
using namespace std;
vector<char> token(1, '8');
stringstream ss;
ss << token.at(0);
int pid = -1;
ss >> pid;
if(!ss) {
cerr << "error: can't convert to int '" << token.at(0) << "'" << endl;
}
cout << pid << endl;
return 0;
}