I've tried so many times in different way to concatenate two strings, one way gives me segment fail,and the other way don't give me error but not it's making the correct function of concatenate. I need result is like this aa, what am I doing wrong?
#include <iostream>
using namespace std;
char str1[20], str2[20], str3[20];
void stringConcat(char[], char[], char[]);
void stringConcat(char str1[], char str2[], char str3[])
{
int i = 0, j = 0;
if (str1[i] != '\0') {
str3[i] = str1[i];
i++;
}
if (str2[j] != '\0') {
str3[i + j] = str2[j];
j++;
}
str3[i] = '\0';
}
int main()
{
int compare;
cout << "First string" << endl;
cin >> str1;
cout << "Second string" << endl;
cin >> str2;
stringConcat(str1, str2, str3);
cout << "result: " << str3 << endl;
return 0;
}
Related
I'm pretty unfamiliar with string manipulation in C++ and I can't seem to wrap my head around how to select characters in strings. Below is my program so far. Whenever I run it, however, the program crashes and an error showing "Thread 1: EXC_BAD..." shows up (I'm working on Xcode). For some reason, simply using input[0] works if I want to print the first character from the string, but doesn't when I do input[x] in a loop.
#include <iostream>
#include <string>
int num, characterCount;
string currentChar, previousChar;
int main()
{
cout << "How many lines of input? \n";
cin >> num;
for (int x = 0; x < num; x++)
{
string input;
cin >> input;
previousChar = input[0];
currentChar = input[1];
characterCount = 0;
int y = 0;
while (currentChar != "")
{
y++;
if (previousChar == currentChar)
{
characterCount++;
}
else if (previousChar != currentchar && currentChar != "")
{
cout << characterCount << " " << previousChar;
characterCount = 0;
}
else if (currentChar == "")
{
cout << characterCount << " " << previousChar;
}
previousChar = currentChar;
currentChar = input[y];
}
}
return 0;
}
Btw I know my code's weird, I'm a beginner in C++. If you have any helpful suggestions feel free to comment!
previousChar = input[0];
currentChar = input[1];
If an empty string was entered, there is no input[0] and there is no input[1], so this becomes undefined behavior.
Your overall problem is checking, incorrectly, when the end of the string has been reached. The shown code attempts to extract a character at each position, place this character into a std::string of its own, and then compare it to an empty string.
This is not the right way to do that. This eventually results in undefined behavior, too, and a likely crash. std::strings have a size() method that give the number of characters in the string, so in your case:
input.size()
gives the number of characters in the string. Which can be 0. Then, you can iterate over each character of the string, and then implement your logic.
The reason you are getting the error is:
currentChar = input[y];
The problem with this line is that input[y] might be inaccessible, for instance your input is "Hello". With the way you wrote your code, y would eventually equals 5. However, you the last letter 'o' is input[4]. Because of that, when y=5, you get an error.
There are couple ways you could fix it. One has already mentioned using .size() to make sure, another one has mentioned using iterator:
for(auto iterator = input.begin();iterator!=input.end();++iterator)
However, what I want to mention is that you should be declaring your currentChar and previousChar as char type instead of string since they would always be single characters. Also, depends on the version of C++ and compiler you are using, if you are using C++11, input[5] on "Hello" is actually fine.
When you passed input[5] to a char currentChar type, currentChar gets a null character. So for you while loop, you could test while(currentChar). When currentChar gets the null character, the while loop would test false, and ends the loop.
Below is how I would change inside your for loop. Most of them stays the same, beside changing previousChar and currentChar into char type, and some condition checkings for them, with some minor changes to refine them.
#include <iostream>
#include <string>
int main() {
int num;
std::cout << "How many lines of input? \n";
std::cin >> num;
for (int x = 0; x < num; x++)
{
std::string input;
std::cin >> input;
char previousChar = input[0];
int y = 1;
char currentChar = input[y];
int characterCount = 1;
while(currentChar)
{
y++;
if (previousChar == currentChar)
{
characterCount++;
}
else
{
std::cout << characterCount << " " << previousChar << "\n";
characterCount = 1;
}
previousChar = currentChar;
currentChar = input[y];
}
std::cout << characterCount << " " << previousChar << "\n";
}
}
Also do note that it feels weird to use a while loop when it is iterating through a index number for me. So I would probably use a for loop instead of the while loop:
#include <iostream>
#include <string>
int main() {
int num;
std::cout << "How many lines of input? \n";
std::cin >> num;
for (int x = 0; x < num; x++)
{
std::string input;
std::cin >> input;
char previousChar = input[0];
int y = 1;
char currentChar = input[y];
int characterCount = 0;
for(int y = 1; currentChar; y++)
{
if (previousChar == currentChar)
{
characterCount++;
}
else
{
std::cout << characterCount << " " << previousChar << "\n";
characterCount = 1;
}
previousChar = currentChar;
currentChar = input[y];
}
std::cout << characterCount << " " << previousChar << "\n";
}
}
And here is how you could do it with iterator:
#include <iostream>
#include <string>
int main() {
int num;
std::cout << "How many lines of input? \n";
std::cin >> num;
for (int x = 0; x < num; x++)
{
std::string input;
std::cin >> input;
char previousChar, currentChar;
previousChar = input[0];
int characterCount = 1;
for(auto it = input.begin()+1; it != input.end();it++)
{
currentChar = *it;
if (previousChar == currentChar)
{
characterCount++;
}
else
{
std::cout << characterCount << " " << previousChar << "\n";
characterCount = 1;
}
previousChar = currentChar;
}
std::cout << characterCount << " " << previousChar << "\n";
}
}
From what I get by reading your code you are trying to print the number of duplicate characters. How I would go about doing this is as follows:
#include <iostream>
#include <string>
int num, characterCount;
int main()
{
std::cout << "How many lines of input? \n";
std::cin >> num;
for (int x = 0; x < num; x++)
{
characterCount=0;
std::string input;
std::cin >> input;
for(auto iterator = input.begin();iterator!=input.end();++iterator)
{
if(iterator == input.end()-1)
std::cout <<"Duplicates: " << characterCount
<< " " <<"Character: "<< *iterator << "\n";
else
{
if(*iterator == *std::next(iterator,1))
characterCount++;
else
{
std::cout <<"Duplicates: " << characterCount
<< " " <<"Character: "<< *iterator << "\n";
characterCount=0;
}
}
}
}
return 0;
}
First of all, you weren't using the std namespace. You need to use std:: like I did below before every call from that particular namespace or you can just using namespace std at the top of the file after the include directives.
Second of all I ditched your algorithm using previous character and current character in favour of an approach using iterators.. A string is a standard c++ container from the standard template library so we can use iterators to go over it (or a standard for loop if you so desire).
The code prints duplicates for each character in the string, much as you wanted to do I think.
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'm trying to make a program that asks the user to input a string then checks to see how many vowels and consonants are in the string, using c strings. Right now I'm working on the function that counts the vowels. I finally got it to were I don't have any errors, but my program just hangs up after choosing to count the vowels. Here is my code.
#include "stdafx.h"
#include <iostream>
#include <string.h>
using namespace std;
class VowelsandConsonants {
public:
int findVowels(char *cString, const int STRINGLEN) {
const int SIZE = STRINGLEN;
int vowelCount = 0;
char *str = cString;
char vowels[5] = { 'a', 'e', 'i', 'o', 'u' };
for (int i = 0; i < SIZE; i++) {
str[i];
for (int j = 0; j < SIZE; i++) {
vowels[j];
if (strcmp(vowels, str)) {
vowelCount++;
}
}
}
return vowelCount;
}
};
int main()
{
char *myString = nullptr;
const int STRLEN = 20;
int selection;
myString = new char[STRLEN];
VowelsandConsonants v;
cout << "Enter a string 20 characters or less." << endl;
cin.getline(myString, STRLEN);
cout << "Select the number of what you want to do." << endl;
cout << "1.) Count the number of vowels." << endl;
cout << "2.) Count the number of consonants." << endl;
cout << "3.) Count both vowels and consonants." << endl;
cout << "4.) Enter another string." << endl;
cout << "5.) Exit program." << endl;
cin >> selection;
if (selection == 1) {
cout << v.findVowels(myString, STRLEN);
}
delete[] myString;
return 0;
}
Am I approaching this the right way?
I recommend using a C-Style string containing the vowels, then using strchr to search it:
const char vowels[] = "aeiou";
const size_t length = strlen(cString);
unsigned int vowel_count = 0;
for (unsigned int i = 0; i < length; ++i)
{
if (strchr(vowels, cString[i]) != NULL)
{
++vowel_count;
}
}
There are other methods, such as using an array to hold the counts (and using the letter as an index) or std::map.
Why the example code below can run fine on Visual Studio. In Eclipse, NetBean or CodeBlock the code can run but can't show the Result? Thanks All.
Ex: input one string.
a/ Uppercase first letter.
b/ Remove spaces inside the string.
#include "iostream"
#include "string.h"
using namespace std;
#define MAX 255
//uppercase first letter
char* Upper(char* input)
{
char* output = new char[MAX];
bool isSpace = false;
for (int i = 0; i < strlen(input); i++)
{
output[i] = input[i];
if (isSpace)
{
output[i] = toupper(output[i]);
isSpace = false;
}
if (output[i] == ' ') isSpace = true;
}
output[strlen(input)] = '\0'; // end of the string
output[0] = toupper(output[0]); // first character to upper
return output;
}
//remove space inside the string
char* RemoveSpaceInside(char* input)
{
char* output = new char[MAX];
strcpy(output, input);
int countWhiteSpace = 0;
for (int i = 0; i < strlen(output); i++)
{
if (output[i] == ' ')
{
for (int j = i; j < strlen(output) - 1; j++) // move before
{
output[j] = output[j + 1];
}
countWhiteSpace++;
}
}
output[strlen(output) - countWhiteSpace] = '\0'; // end of the string
return output;
}
int main()
{
char* name = new char[MAX];
cout << "Enter name: "; cin.getline(name, strlen(name));
cout << "Your name: " << name << endl;
cout << "\n******* Q.A *******\n";
char* qa = Format2VN(name);
cout << qa << endl;
cout << "\n******* Q.B *******\n";
char* qb = RemoveSpaceInside(name);
cout << qb << endl;
return 0;
}
char* name = new char[MAX];
cout << "Enter name: ";
cin.getline(name, strlen(name));
Calling strlen(name) will invoke undefined behavior, because you haven't initialized the array. Poor strlen will try to find the NUL character in an uninitialized byte mess. Definitely not a good idea.
What you probably want is:
cin.getline(name, MAX); // not sure if MAX or MAX-1 or whatever
In general, do yourself a favor and replace char* with std::string. Also, get a good C++ book.
Here is how your example would look like in actual C++:
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
std::string upper_first_letter(std::string s)
{
if (!s.empty()) s[0] = toupper(s[0]);
return s;
}
std::string remove_spaces(std::string s)
{
s.erase(std::remove_if(s.begin(), s.end(), isspace), s.end());
return s;
}
int main()
{
std::string name;
std::cout << "Enter name: ";
std::getline(std::cin, name);
std::cout << name << '\n';
std::cout << upper_first_letter(name) << '\n';
std::cout << remove_spaces(name) << '\n';
}
So right now I have this code that generates random letters in set increments determined by user input.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int sLength = 0;
static const char alphanum[] =
"0123456789"
"!##$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum) - 1;
char genRandom()
{
return alphanum[rand() % stringLength];
}
int main()
{
cout << "What is the length of the string you wish to match?" << endl;
cin >> sLength;
while(true)
{
for (int x = 0; x < sLength; x++)
{
cout << genRandom();
}
cout << endl;
}
}
I'm looking for a way to store the first (user defined amount) of chars into a string that I can use to compare against another string. Any help would be much appreciated.
Just add
string s(sLength, ' ');
before while (true), change
cout << genRandom();
to
s[x] = genRandom();
in your loop, and remove the cout << endl; statement. That will replace all of the printing by putting the characters into s.
Well, how about this?
std::string s;
for (int x = 0; x < sLength; x++)
{
s.push_back(genRandom());
}
#include<algorithm>
#include<string>
// ...
int main()
{
srand(time(0)); // forget me not
while(true) {
cout << "What is the length of the string you wish to match?" << endl;
cin >> sLength;
string r(sLength, ' ');
generate(r.begin(), r.end(), genRandom);
cout << r << endl;
}
}