Sort char array using sort function c++ - c++

I am trying to limit user input into alphabet only, then sort all the character in ascending order.
build messages
error: no matching function for call to 'std::__cxx11::basic_string::basic_string(char&)'
This is my header
#include <iostream>
#include <string.h>
#include <conio.h>
#include <stdio.h>
#include <regex>
should i convert the char into string then convert back to char for my following code ?
string Sortstr (str[mlength]);
sort(Sortstr.begin(), Sortstr.end());
getting this 2 line error.
int mlength = 100;
int main() {
char str[mlength];
int length;
cout << "Please enter a c-string: ";
cin.getline(str,mlength,'\n');
regex pass1("^[a-zA-Z]+");
while(!regex_match(str,pass1)) {
cout<<"Error"<<endl;
cout << "Please enter a c-string: ";
cin.getline(str,mlength,'\n');
}
string Sortstr (str);
sort(str, str + strlen(str));
}

Why not just sort str?
sort(str, str + strlen(str));
There's no reason you can't sort an array directly. Just pass pointers to the first and one-past-the-end elements of your array to sort. In this case adding strlen gets a pointer to the effective end of your array.

In this line
string Sortstr (str[mlength]);
you are using the index operator on a char array which gives you one single char. So, you are passing one single char to the string constructor. This constructor does not exist, hence the error. Even if it existed, you do not want to pass one single char but the entire char array.
What you want is this:
string Sortstr (str);

Related

Assigning char array from ifstream breaks array if adding another char to array

So I have an assignment that uses char arrays instead of strings. You assign the array from a .txt file and ifstream. A function I have to write is to concatenate the array with another array. However, the array breaks if I add any extra char after the initial word, even though I initialized the array with plenty of space.
input.txt
Hi
main.cpp
#include <iostream>
#include <fstream>
ifstream in("input.txt");
int main()
{
char A[50];
in >> A;
cout << A << endl; // expecting to print "Hi"
A[2] = 't';
cout << A << endl; // expecting to print "Hit"
in.close();
return 0;
}
I expected to see:
Hi
Hit
Instead it prints:
Hi
HitpB
Any help?
you forgot to add '\0' char in zero terminated char array, after you replaced value with index 2.

Making array (char) 1 gives error on stdio.h

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.

Character Array of dynamic length

I have written a C++ Function which can be represented as below:
All it does is take a string (this is where it crashes) and reverse it.
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
cout<<"Enter a string: "<<endl;
char *str;
gets(str);
cout<<"Reversed String is: ";
for(int i=strlen(str)-1;i>=0;i--)
cout<<(str[i]);
return 0;
}
I guess there's some kind of memory access violation.
Any clue why this doesn't work?
Error: Segmentation fault (core dumped)
In c++ there is way more easier and less error prone solution to this problem via std::reverse from algorithm. Also its easier to use std::string.
#include <iostream>
#include <algorithm>
int main ()
{
std::string input;
std::cout << "Enter string to reverse: ";
std::cin >> input;
std::reverse(input.begin(),input.end());
std::cout << "Reversed string: " << input << std::endl;
return 0;
}
If you have to do it via char arrays, try this (you dont even need dynamic memory allocation)
#include <iostream>
#include <algorithm>
#include <cstring>
int main ()
{
char input[1024];
puts("Enter string to reverse: ");
fgets(input, 1024, stdin);
std::reverse(input, input + strlen(input));
printf("Reversed string: %s", input);
return 0;
}
Your code isn't c++ style and I recommend you take a look at the answer from Filip (https://stackoverflow.com/a/45903067/4386427)
I'll just address what goes wrong with your code.
When you do
char* str;
all you get is a pointer that can point to a char. You don't get any memory for holding a char. Further the value of the pointer variable str is uninitialized.
So when you do
strlen(str)
you read an uninitialized variable and try to treat this uninitialized value as a C-style string. That is undefined behavior and is very likely to cause a program crash.
You need to make sure that str is initialized before using it. As you want dynamic memory, you could do:
char *str;
str = new(char[100]); // Initialize str to point to a dynamic allocated
// char array with size 100
...
...
delete(str);
But again - I wouldn't use this style in c++ code

How to compare string from a part of a string in the array in C++?

I need help with my problem. I have an array of strings which is string * A.
A = { dog, doom, dorm, dunk, face, fall, falafel, fart }
I need to check how many string "d" in the array which is 4.
I need to check how many string "do" in the array which is 3.
I was to use binary search to find it. My problem is how do I access part of the string in the array and be able to compare it with another string?
The string data type in c++ is, in other words, a char array (char[]), for example:
#include <conio.h>
#include <string>
#include <iostream>
using namespace std;
int main() {
//Declare the array
string foo[3];
//Inserting values in the strings
foo[0] = "First word";
foo[1] = "Second word";
foo[2] = "Third word";
//Show the first word of the first string
cout << foo[0][0];
_getch();
return 0;
}
So you can compare each character with that.

how to extract a number string member from a char array

i want to extract number string values of a char array. Actually I want to extract numbers embeded in file names for some file management. For example if there is a file name as file21 then i want the decimal number 21 from this file name.
How can i extract these values?
I tried the following but it results in an unexpected value. I think it is as a result of the implicit typecasting from the char to int while doing the arthimetic operation.
char * fname;
cout<<"enter file name";
cin>>fname;
int filenum=fname[4]%10+fname[5];
cout<<"file number is"<<filenum;
NOTE:
The filenamse are strictly in the format fileXX, XX being numbers between 01 and 99
You need to subtract '0' to get the decimal value of a digit character:
int filenum=(fname[4]-'0')*10+(fname[5]-'0');
Better yet, you should use atoi:
int filenum = atoi(fname+4);
You're getting undefined behavior because you're never allocating memory for the char* you read into:
char * fname = new char[16]; //should be enough for your filename format
or better yet
char fname[16];
Also, what do you expect:
fname[4]%10+fname[5];
to do? Magically concatenate the numbers?
First, you convert the first char to an int, multiply it by 10, convert the second char to an int and add to the first one. A simple google search for char to int would get you there.
How can i extract these values?
There are an infinite number of ways. One way is to use std::istringstream:
#include <string>
#include <sstream>
#include <iostream>
int main () {
std::string fname;
std::cout << "Enter file name: ";
std::getline(std::cin, fname);
int filenum;
std::istringstream stream(fname.substr(4,2));
if(stream >> filenum)
std::cout << "file number is " << filenum << "\n";
else
std::cout << "Merde\n";
}
Here is the simplest code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int filenum;
string fname;
cout<<"enter file name";
cin>>fname;
string str2 = fname.substr(4,2);
istringstream(str2) >> filenum;
cout<<"file number is"<<filenum;
return 0;
}
If your input is that much defined, the simplest solution is scanf:
int main()
{
int theNumber = 0;
scanf("file%d.txt", &theNumber);
printf("your number is %d", theNumber);
}
Check it out in action, reading from char* instead of stdio: http://codepad.org/JFqS70yI
scanf (and sscanf) also throws in checking for proper input format: returns number of fields read successfully. In this case if return value is any other than 1, the input was wrong.