I need some help checking if the string is a space and then shifting it by one char in the Alphabet I can get the first word but not any after the space.
string Alphabet = "abcdefghijklmnogqrstuvwxyz ";
cout << "Enter your string > " << flush;
cin >> OldString;
int Length = OldString.length();
for (int i = 0; i < Length; i++) {
if(OldString[i] == Alphabet[26]){
NewString = NewString + Alphabet[26] ;
cout << "string found" << endl;
}
else {
Result = Alphabet.find(OldString[i], 0);
cout << Result << endl;
NewString = NewString + Alphabet[Result + 1];
}
}
cin is looking for the end of input string by searching for the first whitespace in the string.
You should rather use std::getline instead.
So your code is going to look like this:
#include <iostream>
#include <string>
std::string OldString;
string Alphabet = "abcdefghijklmnogqrstuvwxyz ";
cout << "Enter your string > " << flush;
std::getline(std::cin, OldString);
int Length = OldString.length();
for (int i = 0; i < Length; i++) {
if(OldString[i] == Alphabet[26]){
NewString = NewString + Alphabet[26] ;
cout << "string found" << endl;
}
else {
Result = Alphabet.find(OldString[i], 0);
cout << Result << endl;
NewString = NewString + Alphabet[Result + 1];
}
}
Related
I'm trying to check a word for repeated letters. For example, words like "supercalifragilisticexpialidocious," and "emphasis," should not have any double letters in it, but words like "different," "mississippi," and "formatting" should. This is what I have at the moment:
You are close, but your approach is using the wrong data type for the input, and it is outputting the result incorrectly.
Try something more like this instead:
#include <iostream> // for cout and cin
#include <string> // for string commands
using namespace std;
bool hasDoubleChars(const string &str) {
for (size_t i = 1; i < str.size(); ++i) {
if (str[i] == str[i-1]) {
return true;
}
}
return false;
}
int main() {
string str;
cout << "Welcome to the DoubleChecker(TM) word checker" << endl;
cout << "=============================================" << endl;
cout << "Enter a word to check: " << endl;
cin >> str;
if (hasDoubleChars(str)) {
cout << "There are double characters in the word " << str << ".";
} else {
cout << "There are no double characters in the word " << str << ".";
}
cout << endl;
return 0;
}
Live Demo
You can loop through each character of a string, then compare the next character in the string to the previous.
Example
#include <iostream>
int main()
{
std::string str = "Mississippi";
for (int i = str.size(); i > 0; i--)
if (str[i] == str[i-1])
std::cout << "- " << str[i] << std::endl;
return 0;
}
I am trying to find even length substrings from the string "000000".It worked fine till index 2 after that it's not producing desired output.My IDE was showing exception unhandled at line :str2=str1.substr(i,k);
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str = "000000";
string str2, str1;
int i = 0;
while (i < str.length())
{
int k = 2;
str1 = str.substr(i);
cout << "\n new substring from " << i << " pos is ";
cout<<str1 << endl;
int len = str1.length();
cout << len << endl;
while (k <= len)
{
cout << "\n" << i << " " << k;
str2 = str1.substr(i, k);
cout << endl << str2;
k = k + 2;
str2.clear();
}
i++;
str1.clear();
}
}
It seems this statement
str2 = str1.substr(i, k);
^^^
does not make sense.
You mean
str2 = str1.substr(0, k);
^^^
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.
We are taking user input and reversing it in the background and asking the user what is the reverse. Then we compare realreverse and userreverse and say that it's correct or how many mistakes were made. Also we are counting sentences with using dots, and the user should end his input with #.
For example:
hi. how are you doing. #
or
hi bro how are u.
im good. #
The problem is my program is only working if the input doesn't contain any spaces.
hihowareyoudoing. thanksimfinebro #
If the input is like that, it's working.
it works
hihowareyoudoing.
thanksimfinebro. #
This 2 column also working
code:
(program shows correct inverse for testing)
#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
int wrongCount = 0;
if (reverseReal.length() != reverseUser.length()) {
cout << "These strings are not comparable." << endl;
}
else {
for (int i = 0; i < reverseReal.length(); i++) {
if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
wrongCount++;
}
}
cout << "Number of mistakes: " << wrongCount << endl;
if (wrongCount == 0){
cout << "gj correct reverse" << endl;
}
}
}
string getReverse(string sentence) {
string reverseResult = "";
for (int i = sentence.length() - 1; i >= 0; i--) {
reverseResult += sentence.substr(i, 1);
}
return reverseResult;
}
int findsnumber(string snumber)
{
unsigned int sentences = 0, index = 0, length;
string searchPattern = ".";
length = snumber.length();
while (index < length)
{
index = snumber.find(searchPattern, index);
if (index != string::npos)
{
index += searchPattern.length();
sentences++;
}
}
return sentences;
}
// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {
while (sentence.find(".") != string::npos) {
int dotFinder = 0;
string sub = "";
dotFinder = sentence.find(".");
sub = sentence.substr(0, dotFinder);
return sub;
}
return "";
}
int main() {
string input = "";
string result = "";
string reverseReal = "";
int i = 1;
cout << "Welcome to my cancer c++ programme." << endl;
cout << "Enter the paragraph with # at the end to end it:" << endl;
while (cin >> input && input != "#") {
result += input + " ";
}
int sentnumber = findsnumber(result);
cout << "Number of sentences in the given string " << sentnumber << endl;
while (result.find(".") != string::npos) {
string sub = "";
string subReverse = "";
string reverse = "";
string reverseson = "";
cout << i << "/" << sentnumber << endl;
sub = getOneSentence(result);
subReverse = getReverse(sub);
cout << "reverse of the sub " << subReverse << endl;
cout << "Sentence " << i << " : " << sub << endl;
cout << "Enter the reverse of your sentence" << endl;
while (cin >> reverse && reverse != "#"){
reverseson += reverse + "";
}
Comparison(subReverse, reverseson);
result = result.substr(result.find(".") + 2, result.length());
i++;
}
cin.ignore();
cin.get();
}
cin does not support input string with spaces. So, to input a string containing spaces you need to use getline()The correct syntax is std::getline(std::cin, input);
Edited Your Code!
#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
int wrongCount = 0;
if (reverseReal.length() != reverseUser.length()) {
cout << "These strings are not comparable." << endl;
}
else {
for (int i = 0; i < reverseReal.length(); i++) {
if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
wrongCount++;
}
}
cout << "Number of mistakes: " << wrongCount << endl;
if (wrongCount == 0){
cout << "gj correct reverse" << endl;
}
}
}
string getReverse(string sentence) {
string reverseResult = "";
for (int i = sentence.length() - 1; i >= 0; i--) {
reverseResult += sentence.substr(i, 1);
}
return reverseResult;
}
int findsnumber(string snumber)
{
unsigned int sentences = 0, index = 0, length;
string searchPattern = ".";
length = snumber.length();
while (index < length)
{
index = snumber.find(searchPattern, index);
if (index != string::npos)
{
index += searchPattern.length();
sentences++;
}
}
return sentences;
}
// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {
while (sentence.find(".") != string::npos) {
int dotFinder = 0;
string sub = "";
dotFinder = sentence.find(".");
sub = sentence.substr(0, dotFinder);
return sub;
}
return "";
}
int main() {
//char input = '\0';
string input = "";
string result = "";
string reverseReal = "";
int i = 1;
cout << "Welcome to my cancer c++ programme." << endl;
cout << "Enter the paragraph with # at the end to end it:" << endl;
getline(cin, input,'#');
result = input;
int sentnumber = findsnumber(result);
cin.clear();
cout << "Number of sentences in the given string " << sentnumber << endl;
while (result.find(".") != string::npos) {
string sub = "";
string subReverse = "";
string reverse = "";
string reverseson = "";
cout << i << "/" << sentnumber << endl;
sub = getOneSentence(result);
subReverse = getReverse(sub);
cout << "reverse of the sub " << subReverse << endl;
cout << "Sentence " << i << " : " << sub << endl;
cout << "Enter the reverse of your sentence" << endl;
cin.clear();
cin.ignore();
getline(cin,reverse,'#');
reverse.erase(reverse.end() - 1, reverse.end());
reverseson = reverse;
Comparison(subReverse, reverseson);
result = result.substr(result.find(".") + 2, result.length());
i++;
}
system("pause");
}
When I debug my program, it outputs a random stream of characters when outputting the asterisked line.
int main ()
{
string inputPuzzle;
cout << "Enter a word or set of words: ";
getline(cin, inputPuzzle);
char* puzzle = new char[inputPuzzle.size()+1];
memcpy(puzzle, inputPuzzle.c_str(), inputPuzzle.size()+1);
puzzle[inputPuzzle.size()+1] = '';
int strikes = 0;
char userInput;
char* userSoln = new char[inputPuzzle.size()];
for (int i = 0; i < inputPuzzle.size(); i++)
{
userSoln[i] = '-';
if (puzzle[i] == ' ')
{
userSoln[i] = ' ';
}
}
bool solved = false;
int numberOfLetters;
for (;;)
{
numberOfLetters = 0;
cin >> userInput;
for (int i = 0; i < inputPuzzle.size(); i++)
{
if (userInput == puzzle[i])
{
numberOfLetters++;
userSoln[i] = puzzle[i];
}
}
if (numberOfLetters == 0)
{
cout << "There are no " << userInput << "'s\n" ;
strikes++;
}
else
{
cout << "There are " << numberOfLetters << " " << userInput << "'s\n";
}
if (userSoln == puzzle)
{
break;
}
if (strikes == 10)
{
break;
}
**cout << "PUZZLE: " << userSoln << "\n";**
cout << "NUMBER OF STRIKES: " << strikes << "\n";
}
if (strikes == 10)
{
cout << "Sorry, but you lost. The puzzle was: " << puzzle;
}
else
{
cout << "Congratulations, you've solved the puzzle!!! YOU WIN!!!!!";
}
}
I've tried clearing cin buffers, but nothing doing. I have all the necessary include files (string and iostream) too, so that isn't the issue, and i have the namespace std above the main method.
This isn't a valid character constant.
puzzle[inputPuzzle.size()+1] = '';
If you intended a terminating character, it should be
puzzle[inputPuzzle.size()+1] = '\0';
or just
puzzle[inputPuzzle.size()+1] = 0;
or you could replace both these lines
memcpy(puzzle, inputPuzzle.c_str(), inputPuzzle.size()+1);
puzzle[inputPuzzle.size()+1] = '';
with strcpy
strcpy(puzzle, inputPuzzle.c_str());
Edit:
You also need to put a terminating character at the end of userSoln before printing it.
userSoln[ inputPuzzle.size() ] = '\0';
puzzle[inputPuzzle.size()+1] = '';
should be
puzzle[inputPuzzle.size()+1] = '\0';
you were trying to add the null terminator to the end of the string to signify the end, but '' is not quite it.