beginner here
i wrote the below in C++, it's a short program that currently takes 2 words as inputs, and outputs the same words back but the words are split into even and odd instead. I would like to be able to do this for 'T' words instead, but I can't figure it out. I would like to be able to first input the number of words that will follow, for example 10. Then to input the words and get T results back. So instead of just 2 words, an unlimited amount with the user specifying.
I need to put the below into a function and go from there sometime, but I want to learn the best technique to do so - any advice please?
Thanks!
Alex
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
string SecondWord;
cin >> SecondWord;
int LengthSecond;
LengthSecond = SecondWord.length();
string EvenSecond;
string OddSecond;
for (int i = 0; i < LengthSecond; i += 2){
EvenSecond += SecondWord[i];
}
for (int i = 1; i < LengthSecond; i += 2){
OddSecond += SecondWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
cout << EvenSecond << " " << OddSecond << endl;
return 0;
}
Think I got it here, I was over-thinking this one
I put it in a for loop, as below - so any number of words can be input, user has to input the number of test cases at the
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int T;
cin >> T;
for (int i = 0; i < T; i++){
string FirstWord;
cin >> FirstWord;
int LengthFirst;
LengthFirst = FirstWord.length();
string EvenFirst;
string OddFirst;
for (int i = 0; i < LengthFirst; i += 2){
EvenFirst = EvenFirst + FirstWord[i];
}
for (int i = 1; i < LengthFirst; i += 2){
OddFirst = OddFirst + FirstWord[i];
}
cout << EvenFirst << " " << OddFirst << endl;
}
return 0;
}
Ultimately, you are performing the same task N times.
First, let's discuss how to store the information. Functionally, we have one string as input which yields two strings as output. std::pair (from <utility>) lets us easily represent this. But for sake of even-odd, std::array might be a better representation for us. Since we have a variable number of words as input, a variable number of std::array will be output. std::vector (from <vector>) is our friend here.
Second, let's discuss how to process the information. Using named variables for each output component does not scale, so let's switch to a fixed array (noted below as array<string,2>. By switching to a fixed array for output, addressing each split becomes a function of the loop index (index % 2). Below is a solution that generalizes on a known split size at compile time.
#include <string>
#include <array>
#include <vector>
#include <iostream>
int main() {
int N;
std::cin >> N;
constexpr const int Split = 2;
using StringPack = std::array<std::string, Split>;
std::vector<StringPack> output;
for (int wordIndex = 0; wordIndex < N; ++wordIndex) {
std::string word;
std::cin >> word;
StringPack out;
{
int index = 0;
for (char c : word) {
out[index % Split] += c;
++index;
}
}
output.emplace_back(out);
}
for (const auto & out : output) {
for (const auto & word : out) {
std::cout << word << ' ';
}
std::cout << '\n';
}
}
Related
Hello guys so this is my code.
I could not use cin nor getline() so I had to use scanf.
It reads all the values in as expected but after entering the last value it says:
free(): invalid pointer ./comp: line 8: 877 Aborted (core dumped) ./$BIN
Anyways, here is the code.
Help would be appreciated.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// n -> amount of lines of code.
// q -> amount of queries.
int n, q;
cin >> n >> q;
// Handle source code Input.
vector<string> v(n);
for (unsigned i = 0; i < n; ++i)
{
cout << "i: " << i << endl;
scanf("%s", &v[i]);
}
return 0;
}
scanf is designed to work with character buffers, not strings. You probably want to use std::string (it's more intuitive and manages memory for you), so scanf is a poor fit. There's a version of getline that works with string.
std::vector<std::string> v(n);
for (int i = 0; i < n; i++) {
cout << "i: " << i << endl;
std::getline(std::cin, v[i]);
}
The %s specifier of scanf() expects a pointer to a char[] array, not a std::string object. By reading directly into a std::string object, you are corrupting its internals.
So, you need to either:
read into a char[] first, then assign that to your std::string:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// n -> amount of lines of code.
// q -> amount of queries.
int n, q;
cin >> n >> q;
// Handle source code Input.
vector<string> v(n);
char buf[256];
for (unsigned i = 0; i < n; ++i)
{
cout << "i: " << i << endl;
scanf("%255s", buf);
v[i] = buf;
/* or:
int len = scanf("%255s", buf);
v[i] = string(buf, len);
*/
}
return 0;
}
pre-allocate the std::string's internal character buffer, then read directly into it (note, this approach is only guaranteed to work in C++11 and later, but in practice will typically work in most implementations of std::string in earlier versions, too):
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// n -> amount of lines of code.
// q -> amount of queries.
int n, q;
cin >> n >> q;
// Handle source code Input.
vector<string> v(n);
for (unsigned i = 0; i < n; ++i)
{
cout << "i: " << i << endl;
v[i].resize(256);
int len = scanf("%255s", &v[i][0]/* or: v[i].data() in C++17 and later */);
v[i].resize(len);
}
return 0;
}
The objective is to create it using user defined functions. such a C++ program which have a user defined function (Name: GenerateRandomWords) whose functionality is to generate random words using english alphabets e.g. Differerent website offer random generated password to use. Save All these words in text File (Name: Output.txt) as well as in an array of type string. The problem I am facing being an amaetuer is that it successfully generates 1st word and stores it in the string but when The loop starts for the second word to be generated the program runs for a while and then ends. this is the code , thanks in advance for the help:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
static const char alphanum[] =
"0123456789"
"!##$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum)-1;
char genRandom()
{
return alphanum[rand() % stringLength];
}
int main()
{
int n = 0, a = 0;
cout << "Howe many strings you want to generate\t";
cin >> n;
cout << "Lenght of each :\t";
cin >> a;
string le;
string ar[] = { "" };
for (int i = 0; i < n; i++)
{
for (int j = 0; j < a; j++)
{
le += genRandom();
}
ar[i] = le;
le = "";
cout << ar[i] << endl;
}
cout << "Out of both loop\n";
for (int i = 0; i < n; i++)
cout << ar[i] << endl;
}
On this line:
string ar[] = { "" };
you are creating an array of strings of size 1. So when you try to add the second string into this array, you invoke undefined behaviour. If you just use a vector<string> you won't have this problem:
vector<string> ar;
and on the line you are doing:
ar[i] = le;
you should do:
ar.push_back(le);
Here's a working demo.
Also, your "random" choices are not very random. Check out the random header for how you can do this better.
According to your requirement, you wants to get the length of each string and the number of strings to be printed using a specified character arrayed variable alphanum and create output.txt to save it.
Consider at the following code:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>
const char alphanum[] =
"0123456789"
"!##$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
void generate(int, int);
void setOutput(char[]);
main(void)
{
int length, strings;
std::cout << "How many strings & length (sep. by SPACE): ";
std::cin >> strings >> length;
srand(time(0));
generate(length, strings);
return 0;
}
void generate(int len, int str)
{
char array[len];
int max = sizeof(alphanum) / sizeof(alphanum[0]);
std::ofstream output("output.txt");
for (int k = 1; k <= str; k++)
{
for (int i = 0; i <= len; i++)
array[i] = alphanum[(rand() % max) + 1];
std::cout << array << std::endl;
output << array << std::endl;
}
}
Output
How many strings & length (sep. by SPACE): 5 5
5Xe*%%
xOD8TQ
YfrM*X
#j&L5&
U8*EYB
Note: Firslty, remember the srand() will let the random values change each time you execute the program. Secondly, this program will generate an output.txt to meet your criteria.
Enjoy!
This program is suppose to generate passwords and compare to what the user inputed, if they match it breaks the while loop and outputs the user's input, but for some reason, the generated passwords are just one characters. I am new to C++, I just started like last Friday.
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
string Password, Passwords;
cout << "Enter a password: ";
getline(cin, Password);
sleep(.7);
system("clear");
while(Password.compare(Passwords)!= 0)
{
for (int x = 0; x <= Password.length(); x++)
{
for (char Alpha = 'a'; Alpha <= 'z'; Alpha++)
{
if(Alpha == 'z')
{
Alpha = 'a';
}
for(int I=0; I <= 10; I++)
{
Passwords = Alpha + I;
system("clear");
sleep(.7);
cout << Passwords <<endl;
}
}
}
}
cout << "Password found: " << Passwords <<endl;
return 0;
}
After a long back and forward in the comments, the OP explained what was his purpose. To generate random words of the same size as input and stop when it matched the input.
This code does what you want. It's in c++14 so you need a recent compiler and to set the c++14 option. Please note the actual use of random.
#include <iostream>
#include <string>
#include <random>
#include <algorithm>
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
class RandomCharGenerator {
private:
static std::string s_chars_;
private:
std::random_device rd_{};
std::default_random_engine r_eng_{rd_()};
std::uniform_int_distribution<int> char_dist_{
0, static_cast<int>(s_chars_.size())};
public:
RandomCharGenerator() = default;
auto getRandomChar() -> char { return s_chars_[char_dist_(r_eng_)]; }
auto setRandomString(std::string &str) -> void {
std::generate(std::begin(str), std::end(str),
[this] { return this->getRandomChar(); });
}
};
std::string RandomCharGenerator::s_chars_ = "abcdefghijklmnopqrstuvwxyz";
auto main() -> int {
RandomCharGenerator rand_char;
auto input = std::string{};
cin >> input;
auto generated = std::string(input.size(), ' ');
do {
rand_char.setRandomString(generated);
cout << generated << endl;
} while (input != generated);
cout << "We generated what you input" << endl;
return 0;
}
For input longer than 4 characters it takes a long time to generate the input.
Ideone demo
To understand why you had only 1 char in your Passwords:
Passwords = Alpha + I;
Alpha is a char, I is an int. Their sum is an int. This is converted to char when assigning to Passwords which is a string. So Passwords is now a string composed of only one char.
It's not clear what that actual line of code was supposed to do, so can't tell you what would have been the fix. Maybe you meant to append to Passwords. Then you should have written Passwords += Alpha + I.
The code below is an example of what I am trying to make. I did not make the code below, am just giving you and example of what am trying to do in the code above
#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
int main()
{
string password;
string Generated;
cout << "Password to find: ";
cin >> password;
char Alpha[]={'a'-1,'a','a','a','a','a','a','a','a','a'};
while( password.compare(Generated) != 0 )
{
Alpha[0]++;
for(int x=0;x<password.length();x++)
{
if (Alpha[x] == 'z'+1)
{
Alpha[x] = 'a';
Alpha[x + 1]++;
}
}
Generated=Alpha[password.length()-1];
for(int i=password.length()-2; i>=0 ; i-- )
Generated+= Alpha[i];
system("clear");
cout << "Trying: "<< Generated << endl;
}
system("clear");
sleep(1);
cout <<"Access Granted: "<< Generated << endl;
return 0;
}
I'm fairly new to C++ and I can't seem to figure this out.
I get some weird output when running it. I am also trying to do this in the simplest way possible. How would I go about just printing the word in the suffix array and not all of the extra stuff. I have tried multiple ways to do this and they still show up.
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main(){
char word1[80];
char word2[80];
char suffix[80];
cout << "Enter the first word: ";
cin >> word1;
cout << "Enter the first word: ";
cin >> word1;
int len1 = strlen(word1);
int len2 = strlen(word2);
while(len1 > 0 && len2 > 0 && word1[len1] == word2[len2]) {
int k=0;
suffix[k]=word1[len1];
k++;
len1--;
len2--;
}
for(int i=strlen(suffix);i>=0; i--){
cout << suffix[i];
}
getch();
return 0;
}
Several things:
You should better use string instead of an array of char. That way,
you don't have to worry about memory.
The line int k=0; should be outside of the while.
Remember that arrays start at 0, so substract 1 from the length of
the words and iterate whilelen1 >= 0 && len2 >= 0
Using strings, you can use the method substr (reference
here).
Here is a modified version of your code:
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main() {
string word1,word2,suffix;
cout << "Enter the first word: ";
cin >> word1;
cout << "Enter the first word: ";
cin >> word2;
int len1 = word1.size()-1;
int len2 = word2.size()-1;
int k=0;
while(len1 >= 0 && len2 >= 0 && word1[len1] == word2[len2]) {
len1--;
len2--;
k++;
}
suffix=word1.substr(word1.size()-k,k);
cout << suffix;
getch();
return 0;
}
I always think the "simplest way possible" is to use someone else's work. Here
is one way to write your program that leverages the standard library:
#include <algorithm>
#include <string>
#include <iostream>
std::string suffix(const std::string& a, const std::string& b) {
size_t len = std::min(a.size(), b.size());
auto its = std::mismatch(a.rbegin(), a.rbegin()+len, b.rbegin());
return std::string(its.first.base(), a.end());
}
int main () {
std::cout << suffix("December", "May") << "\n";
std::cout << suffix("January", "February") << "\n";
std::cout << suffix("April", "April") << "\n";
}
Ok guy i had to make a program to split elements of a string. And after that print those words.
there are some problems i am facing:
1) the array prints more than the size of the words in string i want that it should end printing as soon as last word is printed. i tried to prevent that but it always gives runtime error when i try to break at the last word.
2)is there any other efficient way to split and print ???
#include <sstream>
#include <iostream>
#include<cstdio>
#include<cstdlib>
#include <string>
using namespace std;
int main()
{
std::string line;
std::getline(cin, line);
string arr[1000];
int i = 0;
int l=line.length();
stringstream ssin(line);
while (ssin.good() && i < l)
{
ssin >> arr[i];
++i;
}
int size = sizeof(arr) / sizeof(arr[0]);
for(i = 0; i <size; i++){
cout << arr[i] << endl;
}
return 0;
}
int size = sizeof(arr) / sizeof(arr[0]);
That is a compile time value, and it's always going to be the number of elements in your array (1000). It has no idea how many strings you assigned to in your loop. You stored the number of successfully read strings (plus 1) in the i variable, so you could do this instead:
int size = i - 1;
But if it were up to me, I would just use a growable structure, like vector (#include <vector>)
std::vector<std::string> arr;
std::string temp;
while (ssin >> temp)
{
arr.push_back(temp);
}
for (auto const & str : arr)
{
std::cout << str << std::endl;
}
/* If you're stuck in the past (can't use C++11)
for (std::vector<std::string>::iterator = arr.begin(); i != arr.end(); ++i)
{
std::cout << *i << std::endl;
}
*/
For general purpose character based splitting, I would much prefer boost::split (I know you can't use it, but for future reference)
std::vector<std::string> arr;
boost::split(arr, line, boost::is_any_of(".,;!? "));
Read up on the function strtok. It is old school but very easy to use.
1) there are a couple of changes you should make to your program:
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string line("hello string world\n");
string arr[1000];
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 1000)
{
ssin >> arr[i++];
}
int size = i-1;
for(i = 0; i < size; i++){
cout << i << ": " << arr[i] << endl;
}
return 0;
}
namely, you don't want to print sizeof(arr)/sizeof(arr[0]) (i.e. 1000) elements. There is no point in the condition i < l
2) stringstream is fine if you just want to separate the single strings; if more is needed, use boost/tokenizer for splitting strings. It's modern c++, once you try it you'll never come back!
this is the best method i think no worry now
#include <sstream>
#include <iostream>
#include<cstdio>
#include<cstdlib>
#include <cstring>
#include <string>
using namespace std;
int main ()
{
std::string str;
std::getline(cin, str);
string arr[100];
int l=0,i;
char * cstr = new char [str.length()+1];
std::strcpy (cstr, str.c_str());
// cstr now contains a c-string copy of str
char * p = std::strtok (cstr,".,;!? ");
while (p!=0)
{
//std::cout << p << '\n';
arr[l++]=p;
p = strtok(NULL,".,;!? ");
}
for(i = 0; i <l; i++)
{
cout << arr[i] << endl;
}
delete[] cstr;
return 0;
}