I wrote some code in C++ to display duplicate characters in a string, but if a character is repeated more than three times, the code prints the repeated character more than once.
For example if the string is aaaddbss, it should only print out ads but it prints aaads instead.
What am I doing wrong?
cout << " Please enter a string" << endl;
cin.getline(input, 100); // example input (ahmad wahidy) the output reads a a h a d instead of a h d
for (int i = 0;input[i]!='\0'; i++)
{
for (int j = i+1;input[j]!='\0'; j++)
{
if (input[i] == input[j])
{
cout << input[i] << " ";
}
}
}
cout << endl;
Instead of using your own custom methods, why not use a short and standard method?
Given an std::string input with the text, this will print the unique chars:
std::set<char> unique(input.begin(), input.end());
for (auto & c : unique)
{
std::cout << c << " ";
}
std::cout << std::endl;
You can use std::count and std::set:
#include <string>
#include <set>
#include <iostream>
using namespace std;
int main()
{
string s = "hellohowareyou";
set<char>the_set(s.begin(), s.end());
for (char i:the_set)
if (count(s.begin(), s.end(), i) > 1)
cout << i << endl;
}
Output:
e
h
l
o
If you are not allowed to use a map (and probably also not allowed to use a set), you could simply use an array of integers to count occurrences, with one entry for each possible char value. Note that a character - when taken as an ASCII value - can be directly used as an index for an array; however, to avoid negative indices, each character value should first be converted to an unsigned value.
#include <iostream>
#include <limits>
int main() {
const char* input = "aaaddbss";
int occurrences[UCHAR_MAX+1] = { 0 };
for (int i = 0;input[i] !='\0'; i++)
{
unsigned char c = input[i];
if (occurrences[c]==0) {
occurrences[c]++;
}
else if (occurrences[c]==1) {
occurrences[c]++;
cout << "duplicate: " << c << endl;
}
}cout << endl;
}
Related
Hello how to get all strings until find space and push_back the words until space in the second turn of For loop to start getting all string after space and again until find space that's my code
for example this sentece 5bbbb3 1f a0aaa f1fg3
i want to get bbbb and push_back into in a vector of chars then to push_back aaaa and so
vector of chars vec = vec.[0] == 'bbbb' vec.[1] == 'aaaa' vec.[2] == 'f' vec.[3] == 'ffg'
Thank you in advanced
these are my 2 codes both does not work
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
string sentece;
getline(cin, sentece);
vector<char> words;
for (int i = 0; i < sentece.size(); ++i)
{
while (sentece.substr(i, ' '))
{
if(isalpha(sentece.at(i)))
{
words.push_back(sentece.at(i));
}
}
}
cout << words[0] << '\n';
cout << words[1] << '\n';
cout << words[2] << '\n';
for(const auto& a : words)
{
cout << a;
}
return 0;
}
//==================================================================
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
string sentece;
getline(cin, sentece);
vector<char> words;
for (int i = 0; i < sentece.size(); ++i)
{
while (sentece.at(i) != ' ')
{
if(isalpha(sentece.at(i)))
{
words.push_back(sentece.at(i));
}
if(sentece.at(i) == ' ')
{
break;
}
}
}
cout << words[0] << '\n';
cout << words[1] << '\n';
cout << words[2] << '\n';
for(const auto& a : words)
{
cout << a;
}
return 0;
}
I believe this code should give you the answer you want:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string test = "5bbbb3 1f a0aaa f1fg3";
vector<string> words;
for (int i = 0; i < test.size(); i++)
{
string tmp = "";
while (test[i] != ' ' && i < test.size())
{
if (isalpha(test.at(i))){
tmp += test[i];
}
else if (test.at(i) == ' ')
{
i++;
break;
}
i++;
}
words.push_back(tmp);
}
cout << words[0] << '\n';
cout << words[1] << '\n';
cout << words[2] << '\n';
cout << words[3] << '\n';
}
All you have to do is then replace the test sentence with your user input. You were forgetting to increment i in the while loop so it was examining the same character every time and getting stuck infinitely.
I tried to use as much of your original code as possible so don't assume that this is the most efficient or elegant solution to the problem
Hope this helps :)
You can use character array with scanf()
`
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s[1000];
scanf("%[^' ']%s", s);
cout<<s;
}
This will stop taking input untill you hit enter but this will store string upto only till first occurence of space.
I need solution for this code, its almost done, but i dont understand how i can get first letter from second word, not first? In this code i get 1st letter of first word and dont know how to fix, to get first letter from second word of string which is input from user.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s, krt;
int sk;
cout << "Enter Array: ";
getline(cin, s);
sk = s.length();
cout << "Character in string: " << sk << endl;
int i, vst = 0, bas = 0;
for (i = 0; i < sk; i++) {
krt = s.substr(i, 1);
if (krt == " ")
vst = vst + 1;
}
cout << "Spaces count in string: " << vst << endl;
char tpb;
tpb = s[0];
int pbk;
pbk = tpb;
cout << "String second word first letter: " << tpb << " and its ASCII code: " << pbk << endl;
return 0;
}
Hope you understand what i need to get.
The main problem is that you use 0 as the index, instead of storing the index you want; the first non-space character that follows a space. At least, that is the definition I am going to assume - you didn't specify what to do for multiple consequetive spaces, nor strings containing non-alphabetic characters, such as "function()", where vim would say that '(' is the first character of the second word. Extending the code below to do that is left as an excercise to the reader.
There are a lot of other issues in your code; declarations that can be joined with the definition, doing a string comparison where you only need to compare a single character, and using for loops where there are algorithms to choose instead. Together these add a lot of noise to the code.
Finally, you need some code to handle the case of not having a second word, in order to not get undefined behaviour as in #Diodacus's code.
With regular for-loops:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cout << "Enter Array: ";
getline(cin, s);
const int sk = s.length();
cout << "Character in string: " << sk << endl;
int vst = 0;
bool space_has_passed = false;
int first_nonspace_after_space_index = -1;
for (int i = 0; i < sk; i++) {
if (s[i] == ' ') {
vst = vst + 1;
space_has_passed = true;
} else if (space_has_passed && first_nonspace_after_space_index == -1) {
first_nonspace_after_space_index = i;
}
}
cout << "Spaces count in string: " << vst << endl;
if ( first_nonspace_after_space_index != -1 && sk > first_nonspace_after_space_index) {
const char tpb = s[first_nonspace_after_space_index];
const int pbk = tpb;
cout << "String second word first letter: " << tpb << " and its ASCII code: " << pbk << endl;
} else {
cout << "Need at least two words" << endl;
}
return 0;
}
You can cut it down by 7 lines if you use <algorithms>:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string s;
cout << "Enter Array: ";
getline(cin, s);
const int sk = s.length();
cout << "Character in string: " << sk << endl;
auto first_space = std::find(s.begin(), s.end(), ' ');
auto first_nonspace_afterspace = std::find_if(++first_space, s.end(), [](const char & c){ return c != ' '; });
int count_spaces = std::count(s.begin(), s.end(), ' ');
cout << "Spaces count in string: " << count_spaces << endl;
if( first_nonspace_afterspace != s.end() ) {
const char tpb = *first_nonspace_afterspace;
const int pbk = tpb;
cout << "String second word first letter: " << tpb << " and its ASCII code: " << pbk << endl;
} else {
cout << "Need at least two words" << endl;
}
return 0;
}
I suggest you to take a brief look at the string class documentation page (http://www.cplusplus.com/reference/string/string/), there is a lot of function that can help you manipulate string.
Based on the functions available in this class (eg. cbegin(), cend(), find(), c_str(), etc.), you could do something like this:
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
int main()
{
string s;
cout << "Enter array: ";
getline(cin, s);
int sk = s.length();
cout << "Character in string: " << sk << endl;
int vst = 0;
for (auto i=s.cbegin(); i!=s.cend(); ++i)
if(isspace(*i)) vst++;
cout << "Spaces count in string: " << vst << endl;
string t = s.substr(s.find(" ") + 1, 1);
char tpb = *t.c_str();
int pkt = tpb;
cout << "String second word first letter: " << tpb << " and its ASCII code: " << pkt << endl;
return 0;
}
The main problem is that you print the first letter of the string passed in parameter:
tpb = s[0];
You should either:
memorize the index of the location of the first char of the second word
or
get the second word of the string passed in parameter and print the first char of this string
Finally, what is happening when there is only one word passed ?
You should also think about that. In the code above, if you pass the word test the program prints anyway String second word first letter: t and its ASCII code: 116 which is not true.
Try this:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string s, krt;
int sk;
cout << "Enter Array: ";
getline (cin, s);
sk = s.length();
cout << "Character in string: " << sk << endl;
int i, vst = 0, bas = 0;
for (i = 0; i < sk; i++)
{
krt = s.substr(i, 1);
if (krt == " ") vst = vst + 1;
}
cout << "Spaces count in string: " << vst << endl;
char tpb;
for (i = 0; i < sk; ++i) // Searching for first space
{
if (s[i] == ' ')
break;
}
tpb = s[i + 1];
int pbk;
pbk = tpb;
cout << "String second word first letter: " << tpb << " and its ASCII code: " << pbk << endl;
return 0;
}
This should do the trick.
I'd like to show each letter's ascii code
for example
Input: HelloWorld
Ascii Value: 72 + 101 + 108 ... = 1100
And here's my now-code
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char str[32] = { 0 };
int value = 0, i;
cout << "Input: ";
cin >> str;
for (i=0;i<32;i++)
{
value += str[i];
}
cout << "Ascii Value:" << value << endl;
return 0;
}
I only can take the total value of ascii code such as 1100,
not every code value of each letters such as 7 + 11 + ... = 1100.
How can I fix it?
You should use a string for your input (it's c++, not c). Your for loop sums 32 characters, even if the user inputs a shorter string (the programm will read random values from memory). For conversion from int to char you can use stringstream. This results in
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string input;
std::stringstream sstr;
int value = 0;
std::cout << "Input: ";
std::cin >> input;
for (int i = 0; i < input.size(); i++) {
sstr << int(input[i]) << " + ";
value += input[i];
}
std::string str(sstr.str());
std::cout << "Ascii Value:" << str.substr(0, str.size() - 3) << " = " << value << std::endl;
return 0;
}
I need to pass an user input integer to a sumTotal(& userInt) function.
If the int is 2341 I need to sum 2+3+4+1 = 10 and return the value to main!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// The program needs to input an integer like 2341, then sum it as 2+3+4+1 + 10
// I am in putting an integer and will pass it to a funtion by &.
int main()
{
string strNumber;
int intNumber = 0;
cout << "Enter your number: ";
cin >> intNumber;
// programming the logic for sumTotal(& intNumber) function before creating
strNumber = to_string(intNumber);
cout << "Your number is: " << strNumber << endl;
cout << "Your numbers length: " << strNumber.length() << " digits" << endl;
// here I need to convert the string array to an integer array
for (int i = 0; i < strNumber.length(); ++i){
intNumber[&i] = strNumber[i] - '0';
cout << "Element [" << i << "] contains: " << strNumber[i] << endl;
}
// next a recursive function must sum the integer array
// I am taking an online course and cant afford a tutor please help!
system("pause");
return 0;
}
if you want recursion ,you don't need any string work,try this :
#include <iostream>
using namespace std;
int recSum(int);
int main(){
int i;
cin>>i;
cout<<recSum(i);
return 0;
}
int recSum(int i){
return i==0?0:i%10+recSum(i/10);
}
recursion on array version
#include <iostream>
using namespace std;
int recSum(int* ary,int len){
return len<0?0:ary[len]+recSum(ary,len-1);
}
int main(){
int j[]={1,2,3,4,5,6,7,8,9,10};
cout<<recSum(j,9);
}
A simple and efficient method is to keep the number as a string and access the digits one at a time.
Note the equation:
digit_number = digit_character - '0';
Also, knowing that when summing digits, the order is irrelevant. So, we have:
sum = 0;
for (i = 0; i < string.length(); ++i)
{
sum += string[i] - '0';
}
A string is an array of chars. To convert a char to an int you have to do 'char' - '0'.
I wrote a couple of versions.
Pick whichever one you like best.
#include <iostream>
#include <string>
int main()
{
std::string str = "1234";
int sum = 0;
//pre C++11
for (std::string::iterator i = str.begin(); i != str.end(); ++i)
sum += (*i - '0');
//C++11
sum = 0;
for (auto i = str.begin(); i != str.end(); ++i)
sum += (*i - '0');
//ranged-for
sum = 0;
for (const auto &i : str)
sum += (i - '0');
std::cout << "Sum: " << sum;
std::cin.get();
}
I don't understand why this program is not working.
I need to find the number of occurrences of all characters in three strings by any method.
I used count method but if you guys can help me out with find function so it would be better.
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
string line[3];
int count[3];
cout << "Enter three lines of text...\n\n";
cin >> line[0];
cin >> line[1];
cin >> line[2];
int i;
for(char j='a'; j<=26; j++) {
for(i=0; i<3; i++)
count[i] = std::count(line[i].begin(), line[i].end(), j);
cout << "\n" << j << "\t" << ":" << "\t" << count[i];
}
system ("pause");
return 0;
}
26 is no letter, and (char)26 is normally less than 'a' - so your loop will not execute. Try char j='a';j<='z';j++
I would go for something like this:
#include <map>
#include <string>
#include <iostream>
int main()
{
// Given 3 strings...
std::string s1 = "Hello";
std::string s2 = "Cruel";
std::string s3 = "World";
//===============================================
// THESE 2 LINES ARE ALL YOU NEED FOR COUNTING
std::map<char, int> countMap;
for (char c : (s1 + s2 + s3)) { countMap[c]++; }
//===============================================
// Print the output. This is if you do not care about
// characters that do not appear at all.
for (auto const& e : countMap)
{
std::cout << e.first << ": " << e.second << std::endl;
}
// Print the output. This is if you DO care about
// characters that do not appear at all.
for (char c = ' '; c <= '~'; c++)
{
std::cout << c << ": " << countMap[c] << std::endl;
}
}
http://www.asciitable.com/
Lower case 'a' is 96. Which is less than 26 which is why your loop doesn't execute. Try:
for (char j = 'a'; j <= 'z'; j++)
This will only count the lower case characters. If you wanted the occurrence of lower and upper case you could do this:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string line[3];
cout << "Enter three lines of text...\n\n";
cin >> line[0];
cin >> line[1];
cin >> line[2];
for(char j='a';j<='z';j++)
{
int upper_sum = 0;
int lower_sum = 0;
for(int i=0;i<3;i++)
{
lower_sum += std::count(line[i].begin(),line[i].end(),j);
upper_sum += std::count(line[i].begin(),line[i].end(),j - 32); //32 = 'a' - 'A'
}
cout<<"\n"<<j<<"\t"<<":"<<"\t"<<lower_sum;
cout<<"\n"<<(char)(j - 32)<<"\t"<<":"<<"\t"<<upper_sum;
}
return 0;
}
Here's a correct version of your program:
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
string line[3];
int count[3];
/*cout<<"Enter three lines of text...\n\n";
cin>>line[0];
cin>>line[1];
cin>>line[2];*/
line[0] = "aaaaabbbbbbbbbbb";
line[1] = "ccccccddddddddddd";
line[2] = "kkkkkkkkkkkkk";
int i;
for(char j='a';j<= 'z';j++) // You can loop through the alphabet, but you need to go 'a' to 'z' and not 26
{
for(i=0;i<3;i++)
{ // You were missing these braces, you need them if your loop contains multiple lines
count[i]= std::count(line[i].begin(),line[i].end(),j);
cout<<"\n"<<j<<"\t"<<":"<<"\t"<<count[i];
}
}
system ("pause");
return 0;
}
And here it is in action.
int i;
for(char j='a'; j<=26; j++) {
for(i=0; i<3; i++)
count[i] = std::count(line[i].begin(), line[i].end(), j);
cout << "\n" << j << "\t" << ":" << "\t" << count[i];
}
Your cout line isn't in the inner for loop.
After the inner loop finishes, i is 3. Then cout is called with count[i] which goes out of bounds on the array. Undefined behaviour, you're lucky if it crashes.
Your problem is the i. The place it's declared means it still exists and the cout line can reference it. If you move the declaration to the loop initialiser you'll find the next error:
for(int i=0; i<3; i++)
count[i] = std::count(line[i].begin(), line[i].end(), j);
cout << "\n" << j << "\t" << ":" << "\t" << count[i];
The last line won't compile as i goes out of scope at the end of the loop. I assume you were mistaken in thinking cout was part of the loop, partly due to the poor formatting of the code, and secondly because i was declared at a wider scope.
To correct this, create a block for the for loop by using { and }. This will keep the i in scope for all statements within the block, and repeat the statements for each iteration of the loop.
for(int i=0; i<3; i++) {
count[i] = std::count(line[i].begin(), line[i].end(), j);
cout << "\n" << j << "\t" << ":" << "\t" << count[i];
}