Why is it not working? - c++

I want to create a program that will transform the same words into one. I have a problem with code where I used "while". If I put "if" instead of "while" its working, but not as right as I want, so I need to use "while", but its not working correctly. Its compiling, but not working after inputting the string a.
#include <iostream>
using namespace std;
int main ( ) {
string a;
cout << "Введите string a: ";
getline(cin,a);
for (int i = 0; i < a.length(); i++) {
while (a[i]=a[i+1]) {
for (int z = i; z < a.length(); z++) {
a[z]=a[z+1];
}
}
}
cout << endl << a << endl;
}

while (a[i]=a[i+1]) {
you probably mean
while (a[i]==a[i+1]) {
= is assignment; == is comparison.
When compilomg, pass -Wall to get warnings about this sort of thing. (If a microsoft compiler turning warnings on may require something different; for other compilers, -Wall means "turn on warnings: all normal ones").

Even when I replaced while with if it still wasn't working as you intended. I'm more surprised that you're able to use getline without the string header. You're also assigning the previous character of string a to the next character of a.
Please try this:
#include <iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<string> dupes;
string word;
string a;
cout<<"Enter line:";
getline(cin , a);
int i = 0; //the counter
while(i <= a.length()) {
if(!isspace(a[i])) {
word += a[i];
} if(isspace(a[i])) {
bool present = (find(dupes.begin() , dupes.end() , word) != dupes.end());
if(!present) {
dupes.push_back(word);
word = "";
}
word = "";
}
++i;
}
}
Try your best to avoid nesting loops into one another when possible.

I solved it!
#include <iostream>
using namespace std;
int main ( ) {
setlocale(LC_ALL,"Russian");
cout << "Сборник задач: 7.2" << "\nLv Easy" << "\nExercise #02" << endl << endl;
string a;
cout << "Enter a line: ";
getline(cin,a);
for (int i = 0; i < a.length(); i++) {
for (int j = 0; j < a.length(); j++) {
if (a[i]==a[i+1]) {
for (int z = i; z < a.length(); z++)
a[z]=a[z+1]; } } }
cout << endl << a << endl << endl;
}

Related

How can I get around the use of VLAs?

I have made some code and need to make the length of an array the same as a user input:
#include <iostream>
#include <string>
using namespace std;
void abrev(string word) {
int lastChar = word.length();
if (lastChar > 10) {
cout << word[0];
cout << lastChar - 2;
cout << word[lastChar - 1] << endl;
} else {
cout << word << endl;
}
}
int main() {
int n;
cin >> n;
string words[n];
for (int i = 0; i <= n - 1; i++) {
cin >> words[i];
}
for (int i = 0; i <= n - 1; i++) {
abrev(words[i]);
}
return 0;
}
I don't really know what I could possibly do, I have no ideas. I was using a compiler that just side steps this problem, so I didn't realize it until I submitted this code to codeforces.com, in which I got these errors:
Can't compile file:
program.cpp
program.cpp(20): error C2131: expression did not evaluate to a constant
program.cpp(20): note: failure was caused by a read of a variable outside its lifetime
program.cpp(20): note: see usage of 'n'
program.cpp(23): warning C4552: '>>': operator has no effect; expected operator with side-effect
Also I don't think the last error has anything to do with it, if you could help with that to that would be awesome!
Thankful for any help!
It's mostly duplicated, to resolve the error, it's easy to fix it with std::vector
Since the function abrev doesn't change the argument, it's better to use a const reference.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void abrev(const string& word) {
int lastChar = word.length();
if (lastChar > 10) {
cout << word[0];
cout << lastChar - 2;
cout << word[lastChar - 1] << endl;
} else {
cout << word << endl;
}
}
int main() {
int n;
cin >> n;
std::vector<std::string> words(n);
for (int i = 0; i <= n - 1; i++) {
cin >> words[i];
}
for (int i = 0; i <= n - 1; i++) {
abrev(words[i]);
}
return 0;
}

Check for duplicate characters in C++ Array

I'm trying to create a program where you input 20 characters into an array. Each time you enter a new character, the program should check if that character is already in the array, if it is, print duplicate (but still add the duplicate to the array)
For example, if user types 'a', program should check if 'a' is inside the array.
This is my code:
#include <iostream>
using namespace std;
int main() {
char myAlpha[20];
char input;
cout << "Enter a letter" << endl;
for (int i= 0; i <= 20; i++) {
cin >> input;
for (int k = 0; k <= 20; k++) {
if (myAlpha[k] == input)
cout << "Duplicate" << endl;
}
myAlpha[i] = input;
}
}
I just can't figure out how to make it work, I'm probably missing something stupid. The solution must use something like the code above, no fancy functions or anything.
EDIT: Fixed Code:
#include <iostream>
using namespace std;
int main() {
char myAlpha[20];
char input;
cout << "Enter a letter" << endl;
for (int i= 0; i < 20; i++) {
cin >> input;
for (int k = 0; k < i; k++) {
if (myAlpha[k] == input)
cout << "Duplicate" << endl;
}
myAlpha[i] = input;
}
}
Only problem is that "duplicate" is printed a extra time for each duplication of a letter. For example, if 'a' is entered 3 times, on the 3rd time, "duplicate" is printed 2 times. And so on. But not a big deal.
try this:
#include <iostream>
using namespace std;
int main() {
char myAlpha[20];
char input;
cout << "Enter a letter" << endl;
for (int i = 0; i < 20; i++) {
cin >> input;
myAlpha[i] = input;
for (int k = 0; k < i; k++) {
if (myAlpha[k] == input)
cout << "Duplicate" << endl;
}
}
}
With this line:
char myAlpha[20];
The valid indices of that array are from 0 to 19. However, this line:
for (int i= 0; i <= 20; i++) {
Already implies a bug. Change it to this:
for (int i= 0; i < 20; i++) {
Do the same treatment for the inner for loop line: for (int k = 0; k <= 20; k++) {
But... you'll also need to keep track of how many characters have been inserted instead of looping up to 20 again.
So this is closer to what you want:
int main() {
char myAlpha[20];
char input;
cout << "Enter a letter" << endl;
int inserted = 0;
while (inserted < 20) {
cin >> input;
bool duplicate = false;
for (int k = 0; k < inserted; k++) {
if (myAlpha[k] == input) {
cout << "Duplicate" << endl;
duplicate = true;
break; // no point in continuing to look for duplicates once the first one is found
}
}
if (!duplicate) {
myAlpha[inserted] = input;
inserted++;
}
}
}
Even faster and you can avoid the inner for-loop:
int main() {
bool duplicates[256] = {};
char myAlpha[20] = {};
char input;
cout << "Enter a letter" << endl;
int inserted = 0;
while (inserted < 20) {
cin >> input;
bool duplicate = duplicates[(unsigned char)input];
if (duplicate) {
cout << "Duplicate" << endl;
}
else {
myAlpha[inserted] = input;
inserted++;
duplicates[(unsigned char)input] = true;
}
}
}

How to move word in a circular motion in a string?

I have a string that contains X words (between each word there is a space) I have to move the words in a circular motion to the left according to the number that the user inserts. For example:
"hi my name is aviv and",
the user entered 2. "name is aviv and hi my" I'm looking for legality that repeats itself but I can not find.
Thanks for the guidance. Most importantly, I can not use built-in libraries
Update:
I see there are examples with libraries, I can not use any library.
So what I've done so far.
I wrote a function that gets a string and a number from the user, to move left.
Before sending the string to the function I try to calculate the number of characters I need to move.
My output is - "name is avivhi my"
Regarding the function:
When it gets a string without spaces it works great.
This is my code:
int main()
{
char str[] = "hi my name is aviv";
char str2[] = "hi my name is aviv";
int CountSpace = 0, CountWord = 0;
int Size = 18, flag = 0;
int MoveLeft, Index = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
CountSpace++;
}
}
CountWord = CountSpace + 1;//Understand how many words there are in a string.
cin >> MoveLeft;
if (MoveLeft >= CountWord)//
{
MoveLeft = (MoveLeft - ((MoveLeft / CountWord) * CountWord));//the size of movment;//To reduce the amount of moves if there is such a possibility
}
for (int i = Size - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
flag++;
}
if (flag == MoveLeft)
{
Index = Size - 1 - (i + 1);//That's the amount of characters I have to move
break;
}
}
MoveLeft = Index;
//This code belongs to the function that accepts a string and the amount to move the characters
for (int i = 0; i < Size; i++)
{
if (i + MoveLeft < Size)
{
str[i] = str2[i + MoveLeft];
}
else
{
str[i] = str2[(i + MoveLeft) - Size];
}
}
cout << "Move Left: " << MoveLeft << endl << str << endl << str2 << endl;
return 0;
}
Here's a hint:
vector<string> words = Your_Code_To_Split_Input_Into_Words();
int count = words.size();
int shift = Your_Code_To_Read_Users_Input();
// print the sentence with the rotation specified by shift
for (int i = 0; i < count; i++)
{
int shifted_index = (i + shift) % count; // modulo math implements circular rotation
string spacing = (i == 0) ? "" : " "; // add a space before each word, except first word
cout << spacing << words[shifted_index];
}
cout << endl;
One possible answer, i highly recommend using vectors instead of regular arrays, it's easy and more dynamic, but i didn't use it because you said you can't use built-in libraries.
#include <iostream>
#include<string>
using namespace std;
int main() {
string a[10000];
int counter = 0;
string b = "hi my name is aviv and";
string temp = "";
int userNum = 2;
for(int i=0;i<b.length() ; i++){
if(b[i]!=' '){
temp+=b[i];
}
else if(b[i]==' ' && temp.length()){
a[counter]= temp;
temp = "";
counter++;
}
}
if(temp.length()){
a[counter] = temp;
}
for(int i=userNum;i<=counter+userNum;i++){
cout<<a[i%(counter+1)]<<endl;
}
}
If you can make use of std::rotate() from <algorithm>, this is much easy to do with that. Parse the words using std::stringstream and store to std::vector. Then apply the shif directly to the vector.
Sample Output: https://www.ideone.com/rSPhPR
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
int main()
{
std::vector<std::string> vec;
std::string str = "hi my name is aviv and";
std::string word;
std::stringstream sstr(str);
while(std::getline(sstr, word,' '))
vec.emplace_back(word);
int shift;
std::cout << "Enter the Shift: ";
std::cin >> shift;
std::rotate(vec.begin(), vec.begin() + shift, vec.end());
for(const auto& it: vec)
std::cout << it << " ";
return 0;
}
Here's a snippet :
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define MaxWords 10
int main()
{
stringstream ss;
ss.str("hi my name is aviv and");
string str[MaxWords];
int i;
for (i =0; std::getline(ss, str[i],' ');i++ )
{
cout << str[i] << " ";
}
int n;
cout << "\nEnter pos to split : ";
cin >> n;
for (int j = n; j <= i; j++)
{
cout << str[j] << " ";
}
for (int j = 0; j < n; j++)
{
cout << str[j] << " ";
}
cout << endl;
return 0;
}
Output:

How do I print an array, pause it and continue to print the array in c++?

How do I display 3 names at a time, pausing to let the user press a key before the list continues displaying.
My code now only loops the first 3 values of the array
#include <iostream>
#include <string>
#include <iomanip>
using std::setw;
using namespace std;
int main() {
string a;
string names[10]; //size of array
for (int i = 0; i < 10; i++)
{
std::cout << "Enter name ";
std::cin >> a; //user input
names[i] = a; //assigns input to array
}
cout << "\n";
for (int k = 0; k < 10; k++)
{
for (int j = 0; j < 3; j++)
{
cout << names[j] << endl;
}
system("pause");
}
}
I changed the answer based on your comment. Instead of sleeping we just pause and wait until user inputs anything into the keyboard. Also a note, since you're using namespace, you don't need to include std::, I decided to use it since I was unsure what way you wanted.
#include <iostream>
#include <string>
#include <iomanip>
using std::setw;
using namespace std;
int main() {
string a;
int pauseCheck = 0; //new var
string names[10]; //size of array
for (int i = 0; i < 10; i++) {
std::cout << "Enter name ";
std::cin >> a; //user input
names[i] = a; //assigns input to array
}
cout << "\n";
for (int k = 0; k < 10; k++) {
cout << names[k] << endl;
pauseCheck++; //increments check
if (pauseCheck == 3) { //if equals 3
system("pause"); //we pause till user input
pauseCheck = 0; //reset pause check
}
}
system("pause"); //last and final pause before program ends
}
Here's another way of doing it which I think is a little more straight forward:
#include <iostream>
#include <string>
#include <iomanip>
using std::setw;
using namespace std;
int main() {
string a;
string names[10]; //size of array
for (int i = 0; i < 10; i++)
{
std::cout << "Enter name ";
std::cin >> a; //user input
names[i] = a; //assigns input to array
}
cout << "\n";
for (int k = 0; k < 10; k++)
{
cout << names[k] << endl;
if((k + 1) % 3 == 0) // everytime k + 1 is divisible by 3, let user hit a key
system("pause");
}
}
You can wait for a Enter-Press with another std::cin, just write into an garbage value.
I think other ways are not platform independent. You could ofcourse use the windows api, or unix stuff to get a key press.

why does my counter increase according to the lens of char input in C++

I'm picking up on C++ recently and is trying to code a program which prompts for names for a defined no. of times and inserts each of the input into an array of size-5. The problem happened when I tried to run the following code, my counter, i increases according to the no of len the user input. Why is that so?
#include <iostream>
using namespace std;
int main(){
const int SIZE = 5;
char name[SIZE];
int i;
for (i = 0; i < SIZE; i++){
if (strlen(name) <= 50) {
cout << "Enter a name: \n";
cin >> name[i];
}
}
for (i = 0; i < SIZE; i++){
cout << name[i] << endl;
}
return 0;
}
Output:
if (strlen(name) <= 50) {
You should not call strlen on array which is not initialized.
Use array of strings otherwise
cout << name[i] << endl;
refers to i-th character, not entire string. Or if you want to go with char arrays, you'd need a two dimensional array.
I thing what you indended to do was :
#include <iostream>
using namespace std;
int main(){
const int SIZE = 5;
string names[SIZE];
int i;
for (i = 0; i < SIZE; i++){
cout << "Enter a name: \n";
string name;
cin>>name;
if (strlen(name) <= 50) {
cin >> names[i];
}
}
for (i = 0; i < SIZE; i++){
cout << name[i] << endl;
}
return 0;
}
UNTESTED
The second for loop, which does the output, does this in single characters, incrementing i each time.
To output the string all at once assign a string pointer to name[0] and send that to cout.