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 6 years ago.
Improve this question
Am trying to find If a string has all Unique characters and below is my code, But I get the error "invalid types 'char[int]' for array subscript" in the if statement of the function Unique char, can anyone tell me how to correct this
#include <iostream>
#include<cstring>
using namespace std;
bool unique_char(char);
int main()
{
char s;
bool check;
cout << "Enter any string" << endl;
cin>>s;
check = unique_char(s);
if(check)
cout<<"there are no duplicates";
else
cout<<"the string has duplicates";
return 0;
}
// The if statement in this section has the error
bool unique_char(char s)
{
bool check[256] = {false};
int i=0;
while (s != '\0')
{
if (check **[(int) s[i]]**)
return false;
else
{
check[(int) s[i]] = true;
i++;
}
}
}
You need to pass char array rather than a single char.
int main()
{
char s[1000]; // max input size or switch to std::string
bool check;
cout << "Enter any string" << endl;
cin>>s;
check = unique_char(s);
if(check)
cout<<"there are no duplicates";
else
cout<<"the string has duplicates";
return 0;
}
bool unique_char(char* s)
{
bool check[256] = {false};
int i=0;
while (s[i] != '\0')
{
if (check[(int) s[i]])
return false;
else
{
check[(int) s[i]] = true;
i++;
}
}
return true;
}
Related
I am writing a C++ program for homework, and it needs to count the characters in a char arr[n] string. However, my counter keeps returning the wrong values. I have looked through other answers to similar questions, however, they are not specific to C++ and none of the answers explain the value I am getting.
#include<iostream>
using namespace std;
#include<string.h>
#include <stdlib.h>
class Counter
{
public:
char word[20];
int totChar{ 0 };
void setWord(char word)
{
this->word[20] = word;
}
void setCount(int totChar)
{
this->totChar = totChar;
}
int getLength()
{
return totChar;
}
void charCount()
{
int n = 0;
for (int i = 0; word[i] != '\0'; i++) {
if (word[i] != '\0')
{
n++;
}
}
setCount(n);
}
};
int main()
{
char text[20];
cout << "Enter the string:" << endl;
cin >> text;
Logic input;
input.setWord(text[20]);
input.charCount();
// input.resetWord();
cout << input.getLength();
}
So it seems you haven't figured out how arrays and C strings work in C++ yet.
void setWord(const char* word)
{
strcpy(this->word, word);
}
and
Logic input;
input.setWord(text);
Your code is a bit weird, I guess you are just experimenting, but I think those two changes should make it work.
I'm learning about functions in C++ and I saw this code on Tutorialspoint which tells us whether the
input is an int or a string.
Link to the Tutorialspoint article : https://www.tutorialspoint.com/cplusplus-program-to-check-if-input-is-an-integer-or-a-string
This is the original code:
#include <iostream>
using namespace std;
//check if number or string
bool check_number(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false;
return true;
}
int main() {
string str = "sunidhi";
if (check_number(str))
cout<<str<< " is an integer"<<endl;
else
cout<<str<< " is a string"<<endl;
string str1 = "1234";
if (check_number(str1))
//output 1
cout<<str1<< " is an integer";
else
//output 2
cout<<str1<< " is a string";
}
The original one works perfectly fine, but my code either only shows ouput 1 or only shows output 2 no matter whether you enter an int or a string.
My code:
Note : my code was written on an online compiler. Link to the compiler : https://www.onlinegdb.com
#include <iostream>
using namespace std;
//the function which checks input
bool check(string s){
for(int i = 0; i < s.length(); i++)
if(isdigit(s[i]) != true)
return false;
return true;
}
//driver code
int main(){
string str = "9760";
if(check(str)){
//output 1
cout<<"Thanks! the word was " <<str;
}
else{
//output 2
cout<<"Oops! maybe you entered a number!";
}
}
Ouput when executing my program : Thanks! the word was 9760
Link to the code project: https://onlinegdb.com/HkcWVpFRU
Thank you!
You are checking if the char is a digit and returning false if it is, you should change it to
bool check(string s){
for(int i = 0; i < s.length(); i++)
if(isdigit(s[i])
return false;
return true;
}
a sidenote, if you want to check for false you can do (!bool) instead of (bool != true) it looks cleaner
I've attempted to write a code that checks whether or not a string is a palindrome. Here is the code:
#include <iostream>
#include <string>
using namespace std;
bool pal(string str)//This block of code checks if input string is a palindrome
{
bool valid;
int i;
for (i = 0; i < str.length(); i++)
{
if (str[-i] == str[i])
{
valid = true;
}
else
{
valid = false;
}
}
return valid;
}
int main()
{
string s;
cin >> s;
if (!pal(s))
{
cout << "NO" << endl;
}
else
{
cout << "YES" << endl;
}
return 0;
}
Currently I am getting "Debug Assertion Fail" error.
str[-i] == str[i]
is a problem since negative indices are not valid indices in C++.
You need to change the strategy a little bit.
bool pal(string str)
{
int i = 0;
int j = str.length() - 1;
for ( ; i < j; ++i, --j)
{
if (str[i] != str[j])
{
// No need for any more checks.
return false;
}
}
// If we come here, the string is a palindrome.
return true;
}
C++ Provides us with an inbuilt function reverse() which can be used to reverse the Input string and compare it with un reversed string and print the output. The code goes as follows.
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
string str;
cin>> str;
string rev;
rev = str;
reverse(str.begin(), str.end()); // string reverse operation
if(rev == str){
cout<<"YES"<<endl; // Prints "Yes" if string is palindrome
}else{
cout<<"NO"<<endl; // Prints "No" if string is not palindrome
}
return 0;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I am supposed to write a program that takes in string like "pre#ogrann##mmink#g" and returns "programming", it is like your backspace button is broken and when you hit it you get '#' instead of erasing the char out, and I have to fix it. I have working code here under but it is way to slow, and I might have to deal with huge string, any suggestion how I could do it better/faster?
#include <string>
#include <iostream>
using namespace std;
int main() {
string str;
while(cin >> str) {
bool done = false;
while(!done) {
if((int)str.find('#')>-1) {
str.erase(str.find('#')-1, 2);
} else {
done = true;
}
}
cout << str << endl;
}
}
Here's how I would do it. I haven't tested it to see if it is actually faster, but as it has a complexity of O(N), I think it should be fast enough:
while (std::cin >> input) {
std::string result;
result.reserve(input.length());
for (auto ch : input) {
if (ch == '#') {
if (result.length() > 0)
result.pop_back();
continue;
}
result += ch;
}
std::cout << result << '\n';
}
#include <iostream>
#include <string>
using namespace std;
string s = "pre#ogrann##mmink#g";
int main() {
string out;
int len = s.length();
for (int i = 0; i < len; i++) {
if(s[i] == '#') {
s.erase(i-1,2);
len = s.length();
i -= 2;
}
}
cout << s;
return 0;
}
This produces a working output.
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 6 years ago.
Improve this question
Here is what I have so far. The problem am having now is reading and inserting the strings of words I have in my text file named "word.txt" into the trie tree. I used the "void init()"function to test that the tree functions and it does but using the text file, thats where I don't know how to
any idea please
#include <iostream>
using namespace std;
#include <fstream>
#include <iomanip>
#include <string>
class TrieNode {
public:
// Initialize your data structure here.
TrieNode() {
value = 0;
for (int i=0;i<26;i++){
children[i] = NULL;
}
}
int value;
TrieNode* children[26];
};
class Trie {
private:
TrieNode*root;
int count;
public:
Trie() {
root = new TrieNode();
count = 0;
}
// Inserts a word into the trie.
void insert(string s) {
TrieNode *p = root;
long int len = s.size();
for (int i=0;i<len;i++){
int index = s[i] - 'a';
if (! p->children[index]){
p->children[index] = new TrieNode();
}
p = p->children[index];
}
count++;
p->value = count;
}
// Returns if the word is in the trie.
// -1 if not in trie and not prefix of anything in trie
// 0 if not in trie but is a prefix of something in trie
// 1 if in trie
int search(string key) {
TrieNode *p = root;
long int lenght = key.size();
for (int i=0;i<lenght;i++){
int index = key[i] - 'a';
if (p->children[index]){
p = p->children[index];
}
else{
return -1;
}
}
if (p->value!=0){
return 1;
}
else{
return 0;
}
}
};
//Game class using a tree
class GhostGame{
private:
string row;
ifstream fin;
string wordSoFar = "";
string Player1,Player2;
Trie Tree;
public:
void ReadFile(){
ifstream fin("word.txt");
while (!fin.eof()) { // read file till the end
fin>>row;
getline(fin,row);
cout << row << endl;
Tree.insert(row);
}
//fin.close();
}
void init(){
Tree.insert("ab");
Tree.insert("acd");
}
//start menu
void StartGame(){
init();
cout<<"========================="<<endl;
cout<<"Welcome to Ghost Game"<<endl;
cout<<"========================="<<endl;
//ReadFile();
while(Tree.search(wordSoFar)!=1){
cout<< "Player 1 Insert a letter => ";
cin>> Player1;
cout<<setw(60)<<"now = ["<< wordSoFar <<"]"<<endl;
wordSoFar +=Player1;
if(Tree.search(wordSoFar)==1){
cout<< "Player 2 Wins "<<endl;
break;
}
cout<< "Player 2 Insert a letter => ";
cin>>Player2;
cout<<setw(60)<<"now = ["<< wordSoFar<<"]"<<endl;
wordSoFar += Player2;
if(Tree.search(wordSoFar)==1){
cout<< "Player 1 Wins "<<endl;
break;
}
}
}};
// main driver
int main()
{
GhostGame G1;
G1.StartGame();
return 0;
}
Use regular expressions for such task, they are in header file <regex>. Some good tutorials on regex can be found in book Professional C++ (Wrox) for example.
For file reading use ifstream class from <fstream>.
Open file
using fgets or get line function read the file into temporary string
check first character... Make sure to use tolower, before comparing
void findString(char *filename, char ch)
{
char temp[100];
FILE *infile = fopen(filename, "rw");
while(infile != NULL)
{
fgets(temp,100,infile);
if(tolower(temp[0]) == ch)
cout << temp;
}
fclose(infile);
}