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] >= 'a' && inputnames[z] <= 'z' && inputnames[z 1] == ' ' || inputnames[z] >= 'A' && inputnames[z] <= 'Z' && inputnames[z 1] == ' ') {
counter ;
}
cout << inputnames[z];
}
cout<<endl;
cout << counter;
}
CodePudding user response:
You're looking for word by checking if there's space followed by any other character. Try checking for letters
if(inputnames[z] >= 'a' && inputnames[z] <= 'z') || (inputnames[z] >= 'A' && inputnames[z] <= 'Z')
and if the following character is not a letter.
CodePudding user response:
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;
}