#include <iostream>
#include <string.h>
#include <algorithm>
# define N 100
using namespace std;
int main()
{
char A[N];
unsigned char APP[256] = {0};
cout << "Insert string" << endl;
cin.getline(A,100);
for(int i=0; i < strlen(A); ++i)
{
unsigned char B = A[i];
if(!APP[B])
{
++APP[B];
cout << B;
}
}
return 0;
}
/*char eliminazione(char,char)
{
}*/`
I have to put the for in the "delete" function calling the value B and print it in main, do you know how to do it?
Given a string A read from the keyboard, create a function in C ++ language that calculates a second string B obtained from the first by deleting all the characters that appear more than once. The resulting string must therefore contain the characters of the first string, in the same order, but without repetitions.
Instead of 'cout', you just store the characters into a new string, and increment its index, see code below as an example:
#include <iostream>
#include <string.h>
#include <algorithm>
# define N 100
using namespace std;
int main()
{
unsigned char A[N]; // better to have same type for both A and B
unsigned char B[N];
memset(B, 0, sizeof(B));
unsigned char APP[256] = {0};
cout << "Insert string" << endl;
cin.getline(A,100);
int j = 0;
for(int i=0; i < strlen(A); ++i)
{
unsigned char c = A[i];
if(!APP[c]++)
B[j++] = c; //cout << c;
}
cout << B << endl;
return 0;
}
Output:
Insert string
lalalgdgdfsgwwyrtytr
lagdfswyrt
Related
Basically, I have to show each word with their count but repeated words show up again in my program.
How do I remove them by using loops or should I use 2d arrays to store both the word and count?
#include <iostream>
#include <stdio.h>
#include <iomanip>
#include <cstring>
#include <conio.h>
#include <time.h>
using namespace std;
char* getstring();
void xyz(char*);
void tokenizing(char*);
int main()
{
char* pa = getstring();
xyz(pa);
tokenizing(pa);
_getch();
}
char* getstring()
{
static char pa[100];
cout << "Enter a paragraph: " << endl;
cin.getline(pa, 1000, '#');
return pa;
}
void xyz(char* pa)
{
cout << pa << endl;
}
void tokenizing(char* pa)
{
char sepa[] = " ,.\n\t";
char* token;
char* nexttoken;
int size = strlen(pa);
token = strtok_s(pa, sepa, &nexttoken);
while (token != NULL) {
int wordcount = 0;
if (token != NULL) {
int sizex = strlen(token);
//char** fin;
int j;
for (int i = 0; i <= size; i++) {
for (j = 0; j < sizex; j++) {
if (pa[i + j] != token[j]) {
break;
}
}
if (j == sizex) {
wordcount++;
}
}
//for (int w = 0; w < size; w++)
//fin[w] = token;
//cout << fin[w];
cout << token;
cout << " " << wordcount << "\n";
}
token = strtok_s(NULL, sepa, &nexttoken);
}
}
This is the output I get:
I want to show, for example, the word "i" once with its count of 5, and then not show it again.
First of all, since you are using c++, I would recommend you to split text in c++ way(some examples are here), and store every word in map or unordered_map. Example of my realization you can find here
But if you don't want to rewrite your code, you can simply add a variable that will indicate whether a copy of the word was found before or after the word position. If a copy was not found in front, then print your word
This post gives an example to save each word from your 'strtok' function into a vector of string. Then, use string.compare to have each word compared with word[0]. Those indexes match with word[0] are marked in an int array 'used'. The count of match equals to the number marks in the array used ('nused'). Those words of marked are then removed from the vector, and the remaining carries on to the next comparing process. The program ends when no word remained.
You may write a word comparing function to replace 'str.compare(str2)', if you prefer not to use std::vector and std::string.
#include <iostream>
#include <string>
#include <vector>
#include<iomanip>
#include<cstring>
using namespace std;
char* getstring();
void xyz(char*);
void tokenizing(char*);
int main()
{
char* pa = getstring();
xyz(pa);
tokenizing(pa);
}
char* getstring()
{
static char pa[100] = "this is a test and is a test and is test.";
return pa;
}
void xyz(char* pa)
{
cout << pa << endl;
}
void tokenizing(char* pa)
{
char sepa[] = " ,.\n\t";
char* token;
char* nexttoken;
std::vector<std::string> word;
int used[64];
std::string tok;
int nword = 0, nsize, nused;
int size = strlen(pa);
token = strtok_s(pa, sepa, &nexttoken);
while (token)
{
word.push_back(token);
++nword;
token = strtok_s(NULL, sepa, &nexttoken);
}
for (int i = 0; i<nword; i++) std::cout << word[i] << std::endl;
std::cout << "total " << nword << " words.\n" << std::endl;
nsize = nword;
while (nsize > 0)
{
nused = 0;
tok = word[0] ;
used[nused++] = 0;
for (int i=1; i<nsize; i++)
{
if ( tok.compare(word[i]) == 0 )
{
used[nused++] = i; }
}
std::cout << tok << " : " << nused << std::endl;
for (int i=nused-1; i>=0; --i)
{
for (int j=used[i]; j<(nsize+i-nused); j++) word[j] = word[j+1];
}
nsize -= nused;
}
}
Notice that the removal of used words has to do in backward order. If you do it in sequential order, the marked indexes in the 'used' array will need to be changed. A running test:
$ ./a.out
this is a test and is a test and is test.
this
is
a
test
and
is
a
test
and
is
test
total 11 words.
this : 1
is : 3
a : 2
test : 3
and : 2
I read your last comment.
But I am very sorry, I do not know C. So, I will answer in C++.
But anyway, I will answer with the C++ standard approach. That is usually only 10 lines of code . . .
#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <regex>
// Regex Helpers
// Regex to find a word
static const std::regex reWord{ R"(\w+)" };
// Result of search for one word in the string
static std::smatch smWord;
int main() {
std::cout << "\nPlease enter text: \n";
if (std::string line; std::getline(std::cin, line)) {
// Words and its appearance count
std::map<std::string, int> words{};
// Count the words
for (std::string s{ line }; std::regex_search(s, smWord, reWord); s = smWord.suffix())
words[smWord[0]]++;
// Show result
for (const auto& [word, count] : words) std::cout << word << "\t\t--> " << count << '\n';
}
return 0;
}
I want to know how to check if a word is palindrome in struct data type or object whatever you want to call it. I want to read a data from file then I need to check if that type of word that I have read is a palindrome or not. Also i need to reverse order of the words but I did that so do not need any help about that.
Here is the code:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
struct lettersStr
{
string name;
string object;
};
int main(int argc, char** argv)
{
ifstream letter;
letter.open("letter.txt");
lettersStr things[200];
int numberOfThings= 0;
while(letter >> letter[numberOfThings].name >> letter[numberOfThings].object)
{
numberOfThings++;
}
for (int i = 0; i < numberOfThings; i++)
{
cout << letter[i].name << " " << letter[i].object<< endl;
}
string names;
for (int i = 0; i < numberOfThings; i++)
{
names= things[i].name;
}
for (int i = numberOfThings- 1; i >= 0; i--)
{
cout << things[i].name << endl;
}
bool x = true;
int j = names.length() - 1;
for (int i = 0; i < j; i++,j--)
{
if (things[i].name.at(i) != things[i].name.at(j))
x = false;
if (x)
{
cout << "String is a palindrome ";
}
else
cout << "String is not a palindrome";
}
And here is the cout:
Kayak Audi
Ahmed Golf7
Ahmed
Kayak
String is not a palindrome
String is not a palindrome
I think major problem is this:
for (int i = 0; i < j; i++,j--)
{
if (things[i].name.at(i) != things[i].name.at(j))
x = false;
As you can see it wont cout right way of checking if a word is palindrome or not.
P.S: If this is a stupid question I am sorry, I am a beginner in C++ programming.
Cheers
As already pointed out in the comments, for (int i = 0; i < j; i++,j--) loops though things and the letters of their names simultaneously. You also have to account for cases where you compare a lower and an upper case letter such as the 'K' and 'k' at the beginning and end of 'Kayak'. You can use std::tolower for this.
Here is an example (live demo):
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
bool is_palindrome(std::string name)
{
if (name.empty())
return false;
// As has been pointed out, you can also use std::equal.
// However, this is closer to your original approach.
for (unsigned int i = 0, j = name.length()-1; i < j; i++,j--)
{
if (std::tolower(name.at(i)) != std::tolower(name.at(j)))
return false;
}
return true;
}
struct lettersStr
{
string name;
string object;
};
int main(int argc, char** argv)
{
std::vector<lettersStr> vec = {lettersStr{"Kayak","Boat"},lettersStr{"Audi","Car"}};
for (const auto &obj : vec)
if (is_palindrome(obj.name))
std::cout << obj.name << " is a palindrome" << std::endl;
else
std::cout << obj.name << " isn't a palindrome" << std::endl;
}
It gives the output:
Kayak is a palindrome
Audi isn't a palindrome
Hello I am trying to generate a random array of the length that the user inputs. My array should then print and display the occurences of those letters in the array. So far this only prints up to the letter g and the occurences are incorrect. If someone could tell me what I am doing wrong it would help alot. Thank you.
#include <iostream>
#include <cstring>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(0));
int i, num;
char ch;
char chars[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int freq[26]={0};
cout << "How many letters do you want in your string? ";
cin >> num;
for (i=0; i < num; i++)
{
ch = chars[rand()%26];
chars[i]=ch;
freq[i] +=1;
cout << ch;
}
for (char lower = 'a'; lower <='z'; lower++)
{
cout << "\nLetter" << lower << "is " << freq[lower] << "times";
}
}
Problem 1
The lines
chars[i]=ch;
freq[i] +=1;
are not right. You need to use:
int index = ch - 'a';
freq[index] += 1;
Problem 2
The index in the for loop for printing the data is not correct either.
You need to use:
for (char lower = 'a'; lower <='z'; lower++)
{
int index = lower - 'a';
cout << "\nLetter" << lower << "is " << freq[index] << "times";
}
Important Note
It is worth noting that the C++ standard does not guarantee that lower case letters are contiguous. (Thanks #MartinBonner). For instance, if your system uses EBCDIC encoding your program won't work.
To make your code robust, it will be better to use a std::map.
int main()
{
srand(time(0));
int i, num;
char ch;
char chars[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
std::map<char, int> freq;
// Initialize freq.
for ( ch : chars )
{
freq[ch] = 0;
}
cout << "How many letters do you want in your string? ";
cin >> num;
for (i=0; i < num; i++)
{
ch = chars[rand()%26];
freq[ch] +=1;
}
for (auto item : freq )
{
cout << "\nLetter" << item.first << "is " << item.second << "times";
}
}
You might wanna give a look to C++11 Pseudo-random number generation here is a short way of generating the range that you want using this:
#include <algorithm>
#include <array>
#include <random>
#include <vector>
using namespace std;
int main()
{
int arraySize = 35;
mt19937 engine{random_device{}()};
uniform_int_distribution<> dist{'a', 'z'};
vector<char> vec;
generate_n(back_inserter(vec), arraySize, [&]() { return static_cast<char>(dist(engine); }));
//To count occurrences
array<int, 26> freq;
for (auto c : vec) { ++freq[c-'a']; }
return 0;
}
You should not write into chars, and freq should be extended to cover the a...z range (the ASCII codes), which it does not. Also, increase at index ch, not at i.
I do not even know that range from the top of my head, but it could be modified to track all possible bytes instead (0...255), see result on https://ideone.com/xPGls7
List of changes:
int freq[256]={0}; // instead of int freq[26]={0};
// chars[i]=ch; is removed
freq[ch] +=1; // instead of freq[i] +=1;
Then it works.
Using lambda functions to do most of the work.
#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <ostream>
#include <random>
#include <string>
#include <utility>
#include <vector>
using namespace std::string_literals;
int main()
{
std::mt19937::result_type seed = std::random_device{}();
auto engine = std::mt19937(seed);
auto dist = std::uniform_int_distribution<>('a', 'z');
auto random_letter = [&engine, &dist]() { return static_cast<char>(dist(engine)); };
std::cout << "How many letters do you want to generate? "s;
int n;
if (!(std::cin >> n)) { return EXIT_FAILURE; }
auto letters = std::vector<char>();
std::generate_n(std::back_inserter(letters), n, random_letter);
auto zero = std::map<char, int>();
auto const frequencies = std::accumulate(std::cbegin(letters), std::cend(letters), zero,
[](auto& acc, auto c)
{
++acc[c];
return acc;
});
for (auto const [c, freq] : frequencies)
{
std::cout << "The letter '"s << c << "' appeared "s << freq << " times." << std::endl;
}
return 0;
}
(language : C++)
I have this array:
string myArray[] = {"Apple", "Ball", "Cat"};
Is it possible to store each element in the above array to a new array? Something like this.
char word1[] = myArray[0];
char word2[] = myArray[1];
char word3[] = myArray[2];
I checked the above code, it would throw an error. How would I get this functionality? I cannot use two-dimensional array because I don't know the length of my word in my actual program. A file has the list of words, I would have to read it into the array and get the above string array.
As per the example that you have posted, this is what you are looking for:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
string myArray[] = {"Apple", "Ball", "Cat"};
char test0[myArray[0].length()];
strcpy(test0, myArray[0].c_str());
char test1[myArray[1].length()];
strcpy(test1, myArray[1].c_str());
char test2[myArray[2].length()];
strcpy(test2, myArray[2].c_str());
int i=0;
for(i=0; i<(sizeof(test0)/sizeof(*test0)); i++)
cout<<test0[i]<<" ";
cout<<"\n";
for(i=0; i<(sizeof(test1)/sizeof(*test1)); i++)
cout<<test1[i]<<" ";
cout<<"\n";
for(i=0; i<(sizeof(test2)/sizeof(*test2)); i++)
cout<<test2[i]<<" ";
cout<<"\n";
return 0;
}
In the above code, I have created character arrays test0[], test1[] and test2[] of length equal to the corresponding string in myArray[]. Then I used strcpy() to copy the corresponding string from myArray[] to the character array (test0[], etc). Finally, I just printed these new character arrays.
Working code here.
Note: I am assuming that you are using GCC, since it supports VLAs. If not, then you can use an array of particular length (or better yet, a vector).
Hope this is helpful.
Old style (c++98/c++03):
#include <string>
#include <iostream>
int main()
{
std::string myArray[] = { "Apple", "Ball", "Cat" };
char *firstString = new char[myArray[0].length() + 1];
char *secondString = new char[myArray[1].length() + 1];
char *thirdString = new char[myArray[2].length() + 1];
strcpy(firstString, myArray[0].c_str());
strcpy(secondString, myArray[1].c_str());
strcpy(thirdString, myArray[2].c_str());
std::cout << "firstString = " << firstString << std::endl;
std::cout << "secondString = " << secondString << std::endl;
std::cout << "thirdString = " << thirdString << std::endl;
delete firstString;
delete secondString;
delete thirdString;
return 0;
}
New style (c++11/14):
#include <string>
#include <iostream>
#include <memory>
int main()
{
std::string myArray[] = { "Apple", "Ball", "Cat" };
std::unique_ptr<char> firstString{ new char[myArray[0].length() + 1] };
std::unique_ptr<char> secondString{ new char[myArray[1].length() + 1]};
std::unique_ptr<char> thirdString{ new char[myArray[2].length() + 1]};
strcpy(firstString.get(), myArray[0].c_str());
strcpy(secondString.get(), myArray[1].c_str());
strcpy(thirdString.get(), myArray[2].c_str());
std::cout << "firstString = " << firstString.get() << std::endl;
std::cout << "secondString = " << secondString.get() << std::endl;
std::cout << "thirdString = " << thirdString.get() << std::endl;
return 0;
}
When I input two integers, the output is correctly their difference. However when I enter a string and a char, instead of returning how many times the char appears in the string, it returns -1, which is the out put for error. Could anyone please help me? It's just my second day learing c++...
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void mycount(int a, int b)
{
std::cout<< a - b <<std::endl;
}
void mycount(char str[], char s[])
{
int len,i;
int sum=0;
len = strlen(str);
for (i=0;i<len;i++){
if (strncmp(&str[i],&s[0],1) == 0){
sum = sum + 1;
};
};
printf("results: %d times\n",sum);
}
int main()
{
int a,b;
char c[200],d;
if(std::cin>> a >> b){
mycount(a,b);
}
if(std::cin>> c[200] >> d){
mycount(a,b);
}
else{
std::cout<< "-1" <<std::endl;
}
std::cin.clear();
std::cin.sync();
}
Hint - what will this program print?
#include <iostream>
using namespace std;
int main()
{
char c[200],d;
cout << sizeof(c) << endl;
cout << sizeof(d) << endl;
return 0;
}
Answer:
200
1
That declaration does not do what you think it does - c is an array of 200 chars, d is a single char. It's a feature of the C declaration syntax, same as:
int *c, d;
c is a pointer to int, d is an int.
Since you are doing C++, why not make your life easier and use std::string instead?
A few changes should fix your problems. First when inputting an array with cin use getline and call ignore right before hand. I find it easier to pass s as a char instead of an array of size one make sure your call your second my count with c and d instead of a and b.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void mycount(int a, int b)
{
std::cout<< a - b <<std::endl;
}
void mycount(char str[], char s)
{
int len,i;
int sum=0;
len = strlen(str);
for (i=0;i<len;i++){
if (strncmp(&str[i],&s,1) == 0){
sum = sum + 1;
};
};
printf("results: %d times\n",sum);
}
int main()
{
int a,b;
char c[200],d;
if(std::cin>> a >> b){
mycount(a,b);
}
std::cin.ignore();
if(std::cin.getline (c,200) && std::cin >> d){
mycount(c,d);
}
else{
std::cout<< "-1" <<std::endl;
}
std::cin.clear();
std::cin.sync();
}
These changes should fix it.