Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding all Strings in an array

I tried solving this all day but I cannot find an adequate solution.
I want to print all words of an input char array, but if I type in an empty space at the start or at the end of the array my result is wrong.
Does somebody know how to fix this or does somebody have an understandable solution for me? Thank you!
Using a library would be okay to if it is understandable 🙂

#include <iostream>
#include <ctype.h>
#include <stdio.h>
#include <cmath>
#include <string>
#include <stdlib.h>
using namespace std;

const int len = 1000;
char inputnames[len];
int main()

{
    int counter = 0, z = 0;

    cout << "Type in the Candidates names and press enter please: ";
    cin.getline(inputnames, len);

    counter = 1;
    for (int z = 0; z < len; z++) {
        if (inputnames[z] == ' ') {
            if (inputnames[z + 1] != ' ')
            {
                counter++;
            }
            cout << inputnames[z];
        }
    }
    cout << endl;
    cout << counter<< endl;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t know if I got what is your exact purpose but I can understand the curiosity to solve the issue first you are facing, so please try my changes and let me know if that works for you.

#include <iostream>
#include <ctype.h>
#include <stdio.h>
#include <cmath>
#include <string>
#include <stdlib.h>
using namespace std;

const int len = 1000;
char inputnames[len];
int main()

{
    int counter = 0, z = 0;
    cout << "Type in the Candidates names and press enter please: ";
    cin.getline(inputnames, len);
    counter = 1;
    for (int z = 0; z < len; z++) {
        if (inputnames[z] != ' ') {
           
           cout << inputnames[z];
        }
        else if(z != 0 && inputnames[z] == ' ' && inputnames[z-1] != ' ' && inputnames[z+1] != ' '){
            cout<<"\n";
            counter++;
        }    
            
    }
    cout << endl;
    cout << counter<< endl;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading