code conversion: Matlab to C++ [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a very useful code bit in matlab.
I am using this code bit to save files in different parts of my code, without overwrite existing ones.
Can someone please guide me how to translate this code to C/C++ ?
i=0;
name= ['test_', int2str(i)];
while exist(name)
i=i+1;
name= ['test_', int2str(i)];
end
save(name)

In C++ on Windows I'd use something like :
#include <iostream>
#include<fstream>
#include<string>
#include<sstream>
template <typename T>
std::string num2str ( T Number )
{
std::stringstream ss;
ss << Number;
return ss.str();
}
inline bool if_exists (const std::string& name) {
std::ifstream f(name.c_str());
if (f.good()) {
f.close();
return true;
} else {
f.close();
return false;
}
}
std::string get_next_file( void )
{
int i=1;
while (if_exists("test_" + num2str(i) ) )
i++;
return std::string("test_") + num2str(i);
}

Related

In program while printing the count of the word: "the", from a .txt file containing sentences gives a count=0 even when count of "the" is not zero [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ifstream fin;
char ch[30];
int count = 0;
fin.open("story.txt");
while (!fin.eof())
{
fin>>ch;
if(ch == "the" || ch == "The")
{
count++;
cout<<" "<<ch;
}
}
fin.close();
cout<<" Number of the's in the file : "<<count;
}
Not supposed to use strcompi() function.(or any other functions that could help compare the "ch" with "the")
The count gives zero output because the if condition doesn't work
This is my code, what could be the problem over here.**
You can't compare char arrays with ==, but you can with std::string.
Change
char ch[30];
to
std::string ch;
If you replace char ch[30]; with std::string ch, it looks like it would work. Maybe with some minor adjustments.
The reason why it doesn't work is that ch == "the" tests whether char ch[30], decayed as a pointer, points to the same memory location as the "the" literal. And it doesn't.
If you use a std::string, the operator== for the std::string will be called and it will do the right thing: compare the two strings.

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;
}

strcpy compiles on Windows but it doesn't on Linux [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 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.

How to change a char to a string? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this function:
void map()
{
map<char, string> change;
string usrstr = "A APPLE AND BANANA";
change['A'] = "00011";
change['B'] = "11001";
change['C'] = "01110";
change[' '] = "$$";
}
How would I go about changing all occurrences of 'A' in my string to "00011" and the same for B, C and space. All help is much appreciated
P.S The string wont always be the same
Not sure to understand: how about:
std::string str = "A APPLE AND BANANA";
std::replace(str.begin(), str.end(), "A", "00011" );
std::replace(str.begin(), str.end(), "B", "11001" );
...
You can and should probably use string::replace.
Even with your most recent comment.
But this might have been what you were trying to do:
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <string>
using namespace std;
int main()
{
char temp;
map<char, char*> change;
string lol = "A APPLE AND BANANA";
change['A'] = "00011";
change['B'] = "11001";
change['C'] = "01110";
change[' '] = "$$";
for (int i = 0; i < lol.length(); i++)
{
temp = lol[i];
if (change[temp])
cout << change[temp];
else
cout << lol[i];
}
cout << endl;
cin.get();
return 0;
}

last index of C-style string in C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I tried to write lastindexOf function for my C++ class. After I was trying for 2 weeks, I still can't get it working.
At first , I was trying to follow the logic from this post: CString find the last entry , but since they use CString class instead of char class,I have no success to duplicate the code for char class. I also try the strstr, but I have no luck with that neither. I would appreciate any helps.
here is the code I have came up with so far :
#include
using namespace std;
int lastIndexOf(char *s, char target);
int main()
{
char input[50];
cin.getline(input, 50);
char h = h;
lastIndexOf(input, h);
return 0;
}
int lastIndexOf( char *s, char target)
{
int result = -1;
while (*s != '\0')
{
if (*s == target ){
return *s;
}}
return result;
}
Try this:
int lastIndexOf(const char * s, char target)
{
int ret = -1;
int curIdx = 0;
while(s[curIdx] != '\0')
{
if (s[curIdx] == target) ret = curIdx;
curIdx++;
}
return ret;
}