strcpy compiles on Windows but it doesn't on Linux [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm learning C++ and trying to write universal code (sorry, I don't know how you call the code that can compiles on Windows, Linux, MacOS, etc.).
I have written the function trimLeft:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const string rows = "rows:";
const string columns = "cols:";
const string data = "data:";
struct dimensions {
int rows;
int columns;
};
inline bool exists (const string& name) {
ifstream f(name.c_str());
return f.good();
}
string trimLeft(const string& input) {
if ((input.empty()) ||
((input.at(0) != ' ') && (input.at(0) != '\t')))
return input;
else {
char * tab2 = new char[input.length() + 1];
char *trimmed = new char[input.length() + 1];
strcpy(tab2, input.c_str());
bool skip = true;
int pos = 0;
for (unsigned int i = 0; i < (input.length() + 1); i++) {
if (skip) {
if ((tab2[i] == ' ') || (tab2[i] == '\t'))
continue;
else {
skip = false;
trimmed[pos] = tab2[i];
pos++;
}
}
else {
trimmed[pos] = tab2[i];
if (tab2[i] == '\0')
break;
else
pos++;
}
}
string stringTrimmed(trimmed);
return stringTrimmed;
}
}
It compiles on Windows showing this warning:
warning C4996: 'strcpy': This function or variable may be unsafe.
Consider using strcpy_s instead. To disable deprecation, use
_CRT_SECURE_NO_WARNINGS.
But in Linux, with the following command:
g++ FormatMatrix.cpp -o format
I get:
error: ‘strcpy’ was not declared in this scope
Are headers different on each operating system?
NOTE: And please, stop voting negative: I've got the message.

It is entirely possible that as an implementation detail for a particular compiler, <cstring>, which includes the declaration of strcpy, is included (perhaps much further up the inclusion tree) by another header you included.
To ensure that your code is truly portable and standard conforming include the header files for every class and function you call; never take for granted that you get the functionality of another header by including something different.

Related

C++ [Error] a function-definition is not allowed here before '{' token, I`m trying to change the tables in strcpy into pointers [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 days ago.
Improve this question
So I have this strcpy with tables but I need to change it so that there's no tables and only pointers. When I try to do it, there's an error (I put $$ in front)
So the original:
#include <iostream>
using namespace std;
int main() {
char *mon_strcpy(char destination[], char source[]) {
int index = 0;
while (source[index] != '\0') {
destination[index] = source[index];
index++;
}
destination[index] = '\0';
return destination;
}
return 0;
}
And this is the one I'm trying to make it work:
#include <iostream>
using namespace std;
int main() {
char *mon_strcpy(char *destination, char *source) $${
int index = 0;
while (*source != '\0')
{
*destination = *source;
index++;
}
*destination = '\0';
return destination;
}
return 0;
}
I can't wrap my head around to find the problem.. TIA
In C & C++, you have to declare-define a function outside the other function (here main()). Something like:
char *mon_strcpy(char *destination, char *source) { ... }
int main () {
mon_strcpy(dst, src);
}
Also $$ sign is not allowed to be used inside C++ code except comments.
This just addresses the compiler error you have.
If you have a problem with the function logic, why is it not working? You may want to debug followed by a new question.

strcmp can't convert char* to const char* in a prefix evaluation code (c++) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I'm writing a code to evaluate a prefix expression. The values of the expression are separated by spaces. So if the input is "+ * 87 89 666", I should get 8409 as the answer. The concept of my code is to store the values to an array and then evaluate them value by value. Right now I'm stuck at the switch part because the compiler says invalid conversion from char to const char*
#include <iostream>
#include <bits/stdc++.h>
#include <algorithm>
#include <stack>
#include <string>
#include <sstream>
using namespace std;
char n[99999][6]={};
int evaluatePrefix(int l)
{
stack<int> Stack;
for (int j = l; j >= 0; j--) {
string x=n[j];
if (n[j][0]!='+' || n[j][0]!='-' || n[j][0]!='*' || n[j][0]!='/'){
stringstream ss;
int a;
ss<<x;
ss>>a;
Stack.push(a);
}
else {
int o1 = Stack.top();
Stack.pop();
int o2 = Stack.top();
Stack.pop();
if (strcmp(n[j], '+')==0){
Stack.push(o1 + o2);
}
else if (strcmp(x, '-')==0){
Stack.push(o1 - o2);
}
else if (strcmp(x, '*')==0){
Stack.push(o1 * o2);
}
else if (strcmp(x, '/')==0){
Stack.push(o1 / o2);
}
}
}
return Stack.top();
}
int main()
{
char e[99999], w[99999];
int i=0;
scanf("%[^\n]%*c",e);
char *token = strtok(e, " ");
while (token != NULL)
{
strcpy(n[i], token);
token = strtok(NULL, " ");
}
return 0;
}
You wrote:
if (strcmp(n[j], '+')==0)
n[j] decays into a char*, but '+' is a single char, not a char*. strcmp needs two char pointers.
https://en.cppreference.com/w/c/string/byte/strcmp
So, you should use:
if (strcmp(n[j], "+")==0)

How to extract data from string in C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Note: I am working using C++11 standard
I am looking to write a function that handles the following problem:
Given the following input: a,b,c I want it to print a and b and c
Given: a,b,c, I want it to print a and b and c and ""
Given: ,a I want it to print "" and a
Given , it should print "" and in case of empty string it shouldn't print anything
In other words I want to extract every value between two , plus to take care of the edges.
My current implementation is so buggy and I had edited it more than 8 times since I always find some edge cases.
void print(const string &command)
{
string vertex_title = "";
int i = 0;
while (i < command.lengh()) {
if (command[i] == ',') {
if (i==command.lengh()-1) return false;
std::cout<<vertex_title;
vertex_title = "";
i++;
continue;
}
vertex_title += command[i++];
}
Note: I don't know but maybe regex help here (I know nothing about it)
While you could implement such a function, I'd strongly suggest using existing solutions. There are quite a few.
I'm personally used to absl::StrSplit() (see https://abseil.io/docs/cpp/guides/strings) which by default will do what you want.
Thomas Sablik also wrote in a comment:
You can use boost::algorithm::split or std::strtok
I guess you need this. Even though it's ugly. You can run and debug it step by step.
#include <iostream>
#include <string>
using namespace std;
void print(const string &command)
{
std::string vertex_title = "";
int i = 0;
while (i < command.size()) {
if (command[i] == ',') {
cout << vertex_title;
vertex_title = "";
}
else {
vertex_title += command[i];
}
++i;
if (i == command.size())
cout << vertex_title;
}
}
int main()
{
print("a,b,c");
print("a,b,c,");
print(",a");
print(",");
return 0;
}

C++ String dissapears outside if statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm quite a newbie regarding C++ and I'm struggling with one (maybe simple) thing. I want to write a code that checks the first word of the string line and copy the second word of the string line to the string x_start, x_end or num_steps if the first word of the string is equal to "x_start", "x_end" or "num_steps".
The problem I've to solve is the following. In the if statement the value of the second word (label) is copied to the string x_start, but when I go further to below in my debugger, the content of the string x_start disappears after the if statement end bracket. The first sentence of the output (cout) is now equal to: x_start =, where it should be: x_start = 0.
Does anyone know why this happens and how it can be solved? Thanks in advance!
#include <iostream>
#include <fstream>
#include <cassert>
#include <sstream>
#include <string>
int main(int argc, char** argv) {
std::string x_end;
std::string num_steps;
std::string x_start;
std::string line = "x_start 0";
std::istringstream linestream(line);
while (!linestream.eof()) {
std::string label;
std::string value;
linestream >> label >> value;
if(label.compare("x_start") == 0){
std::string x_start = value;
}
else if(label.compare("x_end") == 0){
std::string x_end = value;
}
else if(label.compare("num_steps") == 0){
std::string num_steps = value;
}
else{
std::cout<<"The format of the text in the file 'params.in' ";
std::cout<<"is not correct"<<std::endl";
break;
}
std::cout<<"x_start = "<<x_start<<std::endl;
std::cout<<"x_end = "<<x_end<<std::endl;
std::cout<<"num_steps = "<<num_steps<<std::endl;
}
return 0;
}
Instead of this
std::string x_start = value;
Write this
x_start = value;
Your code introduces new variable x_start that "hides" the existing variable with the same name. This new variable is set, and immediately afterwards destroyed. So, just don't introduce new variable, and all will be fine.
Repeat this also for x_end and num_steps.
When you do this
if(label.compare("x_start") == 0){
std::string x_start = value;
} //^^^^^^^^^^^
you are telling the compiler the following: "I need a new string variable called x_start. This variable will replace x_start from the outside until the end of the if statement".
This is not what you want, though: you want to assign the existing variable! Removing the declaration will fix this problem:
if(label.compare("x_start") == 0){
x_start = value;
}
Now you are assigning an existing variable - the one that would remain there after the if statement. Of course you need to do the same with other declarations that shadow variables outside of their statements.
Note: the technical term for which variable is visible at what part of your program is scope. Look it up to see what it means and how to work with it.
if(label.compare("x_start") == 0){
std::string x_start = value;
}
Should be
if(label.compare("x_start") == 0){
x_start = value;
}

Segmentation fault, no matter on how i change the code C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
this is my code
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <cstring>
#include <iostream>
using namespace std;
bool endsWith(string const &value, string const &ending)
{
if(value.length() >= ending.length())
{
return (value.compare(value.length() - ending.length(), ending.length(), ending) == 0);
}
return false;
}
void listdir(const char *directory, const char *extension)
{
DIR *dir;
struct dirent *entry;
if(!(dir = opendir(directory)))
{
return;
}
while(entry = readdir(dir))
{
if(entry->d_type == DT_DIR)
{
char path[1024];
int len = snprintf(path, sizeof(path)-1, "%s/%s", directory, entry->d_name);
path[len] = 0;
if(strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0)
{
listdir(path, extension);
}
}
else
{
string file = entry->d_name;
if(endsWith(file, strcat((char *) ".", extension)) || extension == "*")
{
printf("%s \n", entry->d_name);
}
}
}
closedir(dir);
}
int main(int count, char *parameters[])
{
const char *type = "*";
const char *path = ".";
if(count > 1)
{
path = parameters[1];
}
if(count > 2)
{
type = parameters[2];
}
if(count < 1 || count > 3)
{
return 0;
}
listdir(path, type);
return 0;
}
And no matter, what i am doing, i always receive segmentation fault.
Compiling it with g++ under debian is no problem, but running the application puts out always "Segmentation fault"
So what's the matter?
Your error lies in the line strcat((char *) ".", extension), where you try to write data to the memory underlying a string literal.
String literals are loaded into a read only memory segment and trying to write to that causes your segfault.
If you wish to use strcat, you have to provide a target buffer of sufficient size (which is not checked, so using strncat is often preferred). Since this size is undetermined at compile time, you are forced to compute the length of the two strings you wish to append to one another and allocate a buffer of sufficient size with new or malloc.
However, the easiest way of performing a string concatenation in C++ is to forget all about the C equivalents and simply use ::std::string like so:
::std::string s = "hello ";
s += "world";