cannot run program with pointer and fstream in visual studio - c++

I can run my program in codeblock or visual studio 2015 but it doesn't work in visual studio 2017
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
void replacechar(char *filenguon, char ktc, char ktm)
{
fstream fs(filenguon, ios::in | ios::out);
if (!fs)
cout << "khong the tim thay" << endl;
else
{
char ch;
while (fs.get(ch))
{
if (ch == ktc)
{
int pos = fs.tellg();
pos--;
fs.seekp(pos);
fs.put(ktm);
fs.seekg(pos + 1);
}
}
}
}
int main()
{
replacechar("caua.txt", 'r', 'R');
return 0;
}
Error:
Error C2664 'void replacechar(char *,char,char)': cannot convert argument 1 from 'const char [9]' to 'char *'
Error (active) E0167 argument of type "const char *" is incompatible with parameter of type "char *"
Warning C4244 'initializing': conversion from 'std::streamoff' to 'int', possible loss of data
I can run my program in codeblock or visual studio 2015 but it doesn't work in visual studio 2017

Change
void replacechar(char *filenguon, char ktc, char ktm)
to
void replacechar(const char *filenguon, char ktc, char ktm)
The rules about string literals changed in C++11 (I think). They are const data and so any function parameter to which you pass a string literal should be declared with const.
And, as stated in the comments, change
int pos = fs.tellg();
to
auto pos = fs.tellg();
The return from tellg is not an int, by using auto you are asking the compiler to use the correct type, whatever that is.

You are not allowed to pass a const char* (in your case the string literal "caua.txt" to a function accepting a non-const char*.
Change your signature to void replacechar(const char *filenguon, char ktc, char ktm).

Two methods:
1.
void replacechar(const char *filenguon, char ktc, char ktm)
{
//TODO
}
2.
char str[]={"caua.txt";};
replacechar(str, 'r', 'R');
that should be work, "caua.txt" is const char*,it change to char* by copy one by one or const_cast<char*>

Related

Invalid conversion from ‘const char*’ to ‘char*’ with ```rindex``` function

I want to do something with string using the index and rindex function under c++17, but when I compile the program, this error poped up:
debug.cpp: In function ‘int main()’:
debug.cpp:7:27: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
7 | char* index_first = index(str,'c');
| ~~~~~^~~~~~~~~
| |
| const char*
debug.cpp:9:27: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
9 | char* index_last = rindex(str,'c');
| ~~~~~~^~~~~~~~~
| |
| const char*
Then I checked this program online, every function defines of index and rindex I saw are the same:
char* index(const char* s,int c);
char* rindex(const char* s,int c);
And heres my debug code:
#include <stdio.h>
#include <string.h>
int main()
{
const char* str = "abcdefgabcdefg";
char* index_first = index(str,'c');
printf("the first index is %ld\n",index_first - str + 1);
char* index_last = rindex(str,'c');
printf("the last index is %ld\n",index_last - str + 1);
return 0;
}
I compile it using:
g++ -o debug debug.cpp -std=c++17
I want to know why can't I do that and the right way to use index and rindex functions and (or) the right function defines please.
Heres my environment:
Ubuntu LTS 20.04 (x64)
g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Thank you for all the help.
You are trying to assign returned pointers of the type const char * that are used within the functions to pointers of the type char *
Actually the functions you are calling are declared like
const char* index(const char* s,int c);
const char* rindex(const char* s,int c);
In C++ the functions can be overloaded like
const char* index(const char* s,int c);
const char* rindex(const char* s,int c);
and
char* index(char* s,int c);
char* rindex(char* s,int c);
the same way as some other standard C functions as for example the standard C function strchr.
So you should write
const char* index_first = index(str,'c');
printf("the first index is %td\n",index_first - str + 1);
const char* index_last = rindex(str,'c');
printf("the last index is %td\n",index_last - str + 1);
The result of subtracting two pointers has the signed integer type ptrdiff_t. So you need to use the conversion specifier %td instead of %ld.
From the C Standard (7.21.6.1 The fprintf function)
7 The length modifiers and their meanings are:
t Specifies that a following d, i, o, u, x, or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned integer
type argument; or that a following n conversion specifier applies to a
pointer to a ptrdiff_t argument.

What does this error mean? "C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc"

When compiling my program below, I'm getting an error message which I don't really So far, all I'm wanting my code to do is read in a file specified from the command line, and then output a new file with the name changed to having an 'o' at the end.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string output_file_name(string file_name)
{
string output_file_name;
file_name.pop_back();
string ch = "o";
output_file_name=file_name + ch;
return output_file_name;
}
int main(int argc, char **argv)
{
string file_name;
file_name = argv[1];
ifstream input_file(file_name);
ofstream output_file(output_file_name(file_name));
if(input_file.is_open())
{
string line;
while(getline(input_file, line))
{
//will put code here in future
}
}
input_file.close();
return 0;
}
ERROR:
D:\visual studio\VC\Tools\MSVC\14.30.30705\include\string(36): warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc
D:\visual studio\VC\Tools\MSVC\14.30.30705\include\string(83): note: see reference to function template instantiation 'std::basic_istream<char,std::char_traits<char>> &std::getline<char,std::char_traits<char>,std::allocator<char>>(std::basic_istream<char,std::char_traits<char>> &&,std::basic_string<char,std::char_traits<char>,std::allocator<char>> &,const _Elem)' being compiled
with
[
_Elem=char
]
preprocess.cpp(47): note: see reference to function template instantiation 'std::basic_istream<char,std::char_traits<char>> &std::getline<char,std::char_traits<char>,std::allocator<char>>(std::basic_istream<char,std::char_traits<char>> &,std::basic_string<char,std::char_traits<char>,std::allocator<char>> &)' being compiled

strcmp error 'WCHAR [260]' to 'const char *' [duplicate]

This question already has answers here:
error: cannot convert 'const wchar_t [13]' to 'LPCSTR {aka const char*}' in assignment
(3 answers)
Closed 3 years ago.
I'm having trouble by compiling this code in Release mode (it's working perfectly in Debug mode)
#include "MemoryManagement.h"
#include "Windows.h"
#include "Colors.h"
#include <iostream>
#include <TlHelp32.h>
using namespace std;
MemoryManagement::MemoryManagement()
{
handle = NULL;
}
MemoryManagement::~MemoryManagement()
{
CloseHandle(handle);
}
DWORD MemoryManagement::getProcess(const char* proc)
{
HANDLE hProcessId = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
DWORD process = 0;
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof(pEntry);
SetConsoleColor(colors::blue_bright);
cout << "Searching game..." << endl;
while (!process)
{
do {
if (!strcmp(pEntry.szExeFile, proc))
{
process = pEntry.th32ProcessID;
CloseHandle(hProcessId);
handle = OpenProcess(PROCESS_ALL_ACCESS, false, process);
}
} while (Process32Next(hProcessId, &pEntry));
}
SetConsoleColor(colors::green_bright);
cout << "Game found!" << endl << endl;
return process;
}
uintptr_t MemoryManagement::getModule(DWORD procId, const char* modName)
{
HANDLE hModule = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, procId);
MODULEENTRY32 mEntry;
mEntry.dwSize = sizeof(mEntry);
do
{
if (!strcmp(mEntry.szModule, modName))
{
CloseHandle(hModule);
return (DWORD)mEntry.hModule;
}
} while (Module32Next(hModule, &mEntry));
return 0;
}
DWORD MemoryManagement::getAddress(DWORD addr, std::vector<DWORD> vect)
{
for (unsigned int i = 0; i < vect.size(); i++)
{
ReadProcessMemory(handle, (BYTE*)addr, &addr, sizeof(addr), 0);
addr += vect[i];
}
return addr;
}
The error output is this one:
1>c:\users\kuhi\source\repos\cs\cs\memorymanagement.cpp(31): error C2664: 'int strcmp(const char *,const char *)': cannot convert argument 1 from 'WCHAR [260]' to 'const char *'
1>c:\users\kuhi\source\repos\cs\cs\memorymanagement.cpp(31): note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>c:\users\kuhi\source\repos\cs\cs\memorymanagement.cpp(54): error C2664: 'int strcmp(const char *,const char *)': cannot convert argument 1 from 'WCHAR [256]' to 'const char *'
1>c:\users\kuhi\source\repos\cs\cs\memorymanagement.cpp(54): note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>Done building project "CS.vcxproj" -- FAILED.
I see the problem is with strcmp, that I'm giving a wrong data type...
I searched around and didn't find a fix that match my situation...
Why it's working in Debug mode but not in Release mode?
I have to compare 2 strings that can change every time I open the program, so I don't get how to give the arguments as const
It does not make sense for this to work in debug mode; that must be a mis-observation.
WCHAR is a Microsoft alias for wchar_t (or unsigned short if needs be) (ref).
You have an array of these things.
Said array will never be compatible with const char*, because wchar_t and char are two different things. So, you cannot pass your array to functions that require const char*, like strcmp.
C (and, by extension, C++) also provides a wide-character version of strcmp that you can use: wcscmp.

passing literal string as const char * parameter causes code analyzer error

I have overloaded function
int put_message(int level, int sys_log_level, const char * inp_message);
int put_message(int level, int sys_log_level, const std::string &inp_message);
and call this function
put_message(0, LOG_ERR, "clock_gettime error");
Code is compiled and works
but Eclipse CDT Code analyzer says
Invalid arguments '
Candidates are:
int put_message(int, int, const char *)
int put_message(int, int, const ? &)
'
How can I fix this the error?
Update:
After modifying LOG_ERR to int(LOG_ERR) error disappears.
I have not add the in the header.
Adding solves the problem.
you are missing #include <string> or something related to string class
You need to cast the string to the correct type, the compiler treats "some string" as char[] so you need to cast it to const char*
Try with
put_message(0, LOG_ERR, (const char*)"clock_gettime error");

Why std::string reference cannot take char*?

I have simple code.
template<typename T>
class NamedObject{
public:
NamedObject(std::string& name, const T& value):nameValue(name), objectValue(value)
{
}
private:
std::string& nameValue;
const T objectValue;
};
int main(int argc, char* argv[])
{
NamedObject<int> no1("Smallest Prime Number",2);//error
NamedObject<int> no2(std::string("Smalledst Prime Number"),2);//works
return 0;
}
When I make first parameter as non refrence, both no1 and no2 object gets created. But when I keep reference Visual Studio compiler gives following error,
Error 1 error C2664: 'NamedObject::NamedObject(std::string &,const
T &)' : cannot convert parameter 1 from 'const char [22]' to
'std::string &' c:\users\pkothari\documents\visual studio
2008\projects\stackoflw\stackoflw\stackoflw.cpp 36
If char * can be casted to std::string, why not to std::string& ? Is there any way to make it work?
NamedObject<int> no2(std::string("Smalledst Prime Number"),2);//works
That should not work in a standard compliant compiler. It is supported in MS Visual Studio C++ even though it is not standard C++.
Neither of the following calls should work when the expected argument is std::string&.
NamedObject<int> no1("Smallest Prime Number",2);
NamedObject<int> no2(std::string("Smalledst Prime Number"),2);
Both of them should work when the argument type is std::string or std::string const&.