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

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

Related

Why is this code to reverse a word not working? [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 1 year ago.
Improve this question
I'm new to C++. I've written a small code to reverse a word. But it is not showing any output. Please explain.
void * reverse(char * arr)
{
int endindex;
endindex=length(arr)-1;
char * str;
int i=0;
while(endindex>0)
{
str[i]=arr[endindex];
i++;
endindex--;
}
str[i++]=arr[endindex];
str[i]='\0';
cout<< str;
}
Using C++ and the standard library, reversing a string is as simple as:
#include <algorithm> // std::reverse
#include <iostream>
#include <string> // string class
int main() {
std::string str{"Reverse me!"};
std::reverse(str.begin(), str.end());
std::cout << str << '\n';
}
Output:
!em esreveR
As was pointed out, the code above doesn't really help you with your code. My intent was to illustrate that no, you're not really learning C++, but C, and not good C at that. The library <cstring> provides a function strlen(), for example, which calculates a C-string length for you. I take umbrage with beginner assignments that ask you to replicate library functions.
Since I feel that the comments under your question help you sufficiently with your code, here's my take a more C-like approach:
#include <cstring>
#include <iostream>
/*
* Function to reverse the characters of a C-string
*
* Return: None
*
* Parameters:
* str: The string to be reversed; is reversed in-place
*
* NOTES:
* - Normally, when passing a C-array, you should always pass
* the size along as well. Since this function caters
* exclusively to C-strings, I'll make an exception
*/
void reverse_c_string(char* str) {
// My preference for the foor loop is minor, but
// better contains the variables concerned with the loop
for (int i = 0, endIdx = std::strlen(str) - 1; endIdx > i; ++i, --endIdx) {
int tmp = str[i];
str[i] = str[endIdx];
str[endIdx] = tmp;
}
}
int main() {
char phrase[] = "Reverse me!";
std::cout << phrase << '\n';
reverse_c_string(phrase);
std::cout << phrase << '\n';
}
Output:
Reverse me!
!em esreveR

Recursion to count words and redundant words in a sentence in c++ [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 2 years ago.
Improve this question
Hi i'm trying to count the words in a sentence that is input by the user and this is the code i've written
void Count_Words( )
{
int count=0;
for (i = 0; inserted_text[i] != '\0';i++)
{
if (inserted_text[i] == ' ')
count++;
}
cout << "Word Count: " << count + 1;
}
I need to write this using recursion but i can't figure out how.
Also i need to count the redundant words in the sentence using recursion how do i do that?
I can't use mapping i need to use basic logic to do this. Is there anyway i can do this only with basic logic?
I agree with Hatted Rooster (this is not a good fit for recursion). I guess it serves a teaching purpose. So here is another option.
countWords() returns the number of words for the given substring until its end. To calculate the words for substring 0..n, we can calculate the words for substring 1..n first. And if character 0 is a space, add 1 to that.
int countWords(const char* str)
{
if(*str == '\0')
return 1; // last word
return countWords(str + 1) // how many words are in the remaining substring?
+ (*str == ' ' ? 1 : 0); // count if the beginning of the current substring is a space
}
int main()
{
std::string input = "test test test";
std::cout << countWords(input.c_str()); // 3
}
It doesn't really make sense to use recursion here but anyway, this would be one way to do it:
void Count_Words(int& i, const std::string& inserted_text, int& count)
{
if (inserted_text[i] == '\0')
{
++count; // last word
return;
}
if (inserted_text[i] == ' ')
++count;
Count_Words(++i, inserted_text, count); //recurse
}
int main()
{
std::string input = "test test test";
int i = 0;
int count = 0;
Count_Words(i, input, count);
std::cout << count; // 3
}
The thing to take away from this code is that references are a powerful tool to achieve correct recursion as seen in the function parameters.
As the other answer stated, this is really not a problem that should be resolved using recursion. What if there are thousands of words? That would exhaust the stack memory at some point.
In any event, here is one way to do this recursively:
#include <sstream>
#include <string>
#include <iostream>
void Count_Words(std::istringstream& strm, int& count)
{
std::string word;
if ( strm >> word ) // if there is a word, then increment the count
{
++count;
Count_Words(strm, count); // go to next word recursively
}
}
int Count_Words(std::string inserted_text)
{
// This is the setup for the recursive calls
std::istringstream strm(inserted_text);
int count = 0;
// start the recursion
Count_Words(strm, count);
return count;
}
int main()
{
std::string test = "This has four words";
std::cout << Count_Words(test);
}
Output:
4

Logical Issue or Syntax issue with sorting String function

I'm new to C++ and coding in general. I'm attempting to make a simple program that essentially takes in two words and will tell you if these two words are anagrams or not.I also understand that there is likely a pre-made function to sort a string, like an array however I am trying to grasp the concept itself and hence why I'm attempting to make the function.
Here is a quick snippet of the code I've written so far.
Snippet of code
The issue that I'm currently having is that when I call the function to sort the string, the string isn't sorted! Sorry if there is a simple solution to this, I'm fairly new. Is this a logical issue or syntax based? Thank you so much!
#include <iostream>
#include <string>
using namespace std;
//Function Declarations
string sortString(string user_input);
//Program Body
int main()
{
string user_input_one, user_input_two;
cout << "Welcome to Sandip's Anagram Checker! \nPlease Input two words that you'd like the check!";
sortString(user_input_one);
sortString(user_input_two);
if (user_input_one == user_input_two)
cout << "These two words are Anagrams of each other!";
else
cout << "These are not Anagrams!";
return 0;
}
//Function Definations
string sortString(string user_input)
{
string temp_string = user_input;
int i,j;
for (i = 0; i<user_input.length();i++)
{
for (j=0; j<user_input.length();j++)
{
if (user_input[i] == user_input[j])
{
temp_string[i] = user_input[j];
}
else if (user_input[i] > user_input[j])
{
temp_string[i] = user_input[j];
}
else if (user_input[i] < user_input[j])
{
temp_string[i] = user_input[i];
}
}
}
return temp_string;
}
Adding to Daniel's answer, you don't need a temporary string in the sorting function, just process the passed string and return it. Also consider supporting letter cases as well, you can use std::transform from the STL algorithm library.
#include <algorithm>
Add this before looping in your sorting function or after taking inputs in main.
transform(user_input.begin(), user_input.end(), user_input.begin(), ::tolower);
There are a couple issues. You're not actually reading any user input. You can fix this by adding cin >> user_input_one >> user_input_two;.
Your sorting also doesn't work quite right. It looks similar to selection sort, so I tweaked it to be a variation of that. For each character in the string, it goes through the rest of the string and swaps letters if the later one should be first.
string temp_string = user_input;
int i, j;
for (i = 0; i < user_input.length(); i++)
{
for (j = i + 1; j < user_input.length(); j++)
{
if (temp_string[j] < temp_string[i]) {
swap(temp_string[i], temp_string[j]);
}
}
}
return temp_string;
Lastly, as #cigien commented, you aren't using the sorted result. You can change this by replacing your lines calling sortstring() with this:
user_input_one = sortString(user_input_one);
user_input_two = sortString(user_input_two);

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.

code conversion: Matlab to 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 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);
}