I've made a program that shortens full names to initials, and removes any spaces between what has been entered. It did work before but now it prints the initials but also random symbols? I can't really figure out why it's doing it. I'm new to programming also.
This is my code:
// This code removes the spaces from the inputted name
char *removeSpaces(char *str)
{
int i = 0, j = 0;
while (str[i])
{
if (str[i] != ' ')
str[j++] = str[i];
i++;
}
str[j] = '\0';
return str;
}
// This code takes the users name, and shortens (sh) it
int main(void) {
char str[100],sh[20];
int j=0;
cout<<"Enter Full Name :";
cin.getline(str,30);
for(int i=0;i<strlen(str);i++)
{
if(i==0){
sh[j]=str[i];
sh[++j]=' ';
}
else if(str[i]==' '){
sh[++j]=str[i+1];
sh[++j]=' ';
}
}
// This then takes the remove spaces code, and prints the initials with a new line
cout << removeSpaces(sh) <<endl;
cout << "\n" <<endl;
return 0;
}
Picture of the output
You are missing adding string terminator character ('\0') to string sh. Below is the program.
#include <stdio.h>
char *removeSpaces(char *str)
{
int i = 0, j = 0;
while (str[i])
{
if (str[i] != ' ')
str[j++] = str[i];
i++;
}
str[j] = '\0';
return str;
}
// This code takes the users name, and shortens (sh) it
int main(void) {
char str[100],sh[100];
int j=0;
cout<<"Enter Full Name :";
cin.getline(str,30);
for(int i=0;i<strlen(str);i++)
{
if(i==0){
sh[j]=str[i];
sh[++j]=' ';
}
else if(str[i]==' '){
sh[++j]=str[i+1];
sh[++j]=' ';
}
}
sh[j+1] = '\0';
// This then takes the remove spaces code, and prints the initials with a new line
cout << removeSpaces(sh) <<endl;
cout << "\n" <<endl;
return 0;
}
Enter Full Name :ra me ge
rmg
You have missed out a line (I guess) after the for loop in your main function, which means your string is potentially not null-terminated.
Using the same (correct) logic you have in your removeSpaces function, just add this line immediately after the for loop in main:
sh[++j] = '\0';
You don't terminate sh with \0 after you're done, yet removeSpaces() expects a null character at the end of the string. Because of this, removeSpaces() could go past your intended boundary.
Just add this line after your for in main():
sh[++j] = '\0\;
Word of warning: You should always make sure that j is < 20 (the size of sh) before you set it. Otherwise, you could go past the boundary of sh. That could also become a source of problems.
Related
my professor asked us to determine the number of vowels in userString without a call to the library.
I am using '\0' in a for loop to figure out when will the string the user input will come to an end because I don't know the exact size they are going to input for the string. I am a beginner programmer so please don't give me complcated answer! thanks.
I have for(int i = 0; userString[i] != '\0'; i++)
but the program is treating the space bar as a null character too so
I get a problem in the output,
if I have a space in the commend line is treats it as a null and terminates the proram
loop at the pictue of the 2 different outputs for refrence.
As you can see in output 1
When i have "MianJalal" I get 9 in the terminal but for
output 2 When I have "Mian Jalal" (with a space), it treats the space as null and gives me 4, I am aware that '\0' is space in the special chartacer in c++ but it's also null, how can I tell the program i mean null not space?
this is my code,
#include <iostream>
using namespace std;
int main()
{
int numOfVowels = 0;
int length = 0;
char userString[50]; // The string the user will input
cout << "Enter a sentence to find out how many vowels are in the sentence" << endl;
cin >> userString;
for(int i = 0; userString[i] != '\0'; i++) // '\0' means null in a string in c++; if a user doesn't use a index in a char string
{ // the program will know it's a null in syntax '\0'
if(userString[i] == 'A' or userString [i] == 'a' or userString[i] == 'i')
{
numOfVowels++;
}
length++;
}
cout << length << endl;
return 0;
}
The problem is that the operator >> uses the space as a delimiter. So when reading userString it stops at the first space. To avoid this a method could be to use istream::getline (char* s, streamsize n ) function, that reads the entire line up to the '\n' character, or the supplied size limit.
#include <iostream>
using namespace std;
int main()
{
int numOfVowels = 0;
int length = 0;
char userString[50]; // The string the user will input
cout << "Enter a sentence to find out how many vowels are in the sentence" << endl;
cin.getline(userString, sizeof(userString));
for(int i = 0; userString[i] != '\0'; i++) // '\0' means null in a string in c++; if a user doesn't use a index in a char string
{ // the program will know it's a null in syntax '\0'
if(userString[i] == 'A' or userString [i] == 'a' or userString[i] == 'i')
{
numOfVowels++;
}
length++;
}
cout << length << endl;
return 0;
}
Write a program that asks the user to enter their name. First Name and Last Name are entered separately by the user. The program then tells the following:
• Which part (First name, or Last name), has more character, and how many more characters.
• Total number of vowels used in the complete name.
• Tells the user if the First Name and Second Name are same.
This is my assignment and we cannot use strings library. We are supposed to use the character arrays to go about doing this.
Up till now I haven't been able to understand how can I figure out the number of indexes I use to store characters.
int count = 0;
cout << "Enter you first name: ";
char arr[10];
cin.getline(arr, 10);
for (int i = 0; i < 10; i++) {
if (arr[i] != ' ') {
count++;
}
else {
break;
}
}
int x= sizeof(arr) / sizeof(arr[10]);
cout << arr;
cout << endl << count<< endl<<x;
return 0;
but still I haven't come around to a solution.
I was using the wrong character for comparison. I should have used \0 but I was using ' '.
for (int i = 0; i < 10; i++) {
if (arr[i] != '\0') {
count++;
}
else {
break;
}
}
This is the question that needs to be implemented:
Write a C++ program that stops reading a line of text when a period is
entered and displays the sentence with correct spacing and capitalization. For this program, correct spacing means only one space between words, and all letters should be lowercase, except the first letter. For example, if the user enters the text "i am going to Go TO THe moVies.", the displayed sentence should be "I am going to go to the movies."
I have written my piece of code which looks like this:
// Processing a sentence and verifying if it is grammatically correct or not (spacing and capitalization)
//#include <stdio.h>
//#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
cout << "Enter the sentence: ";
getline(cin, sentence);
int len = sentence.length();
// Dealing with capitalizations
for (int j = 0; j <= len; j++)
{
if (islower(sentence[0]))
sentence[0] = toupper(sentence[0]);
if(j>0)
if(isupper(sentence[j]))
sentence[j] = tolower(sentence[j]);
}
int space = 0;
do
{
for (int k = 0; k <= len; k++)
{
if(isspace(sentence[k]))
{
cout << k << endl;
int n = k+1;
if(sentence[n] == ' ' && n <=len)
{
space++;
cout << space <<endl;
n++;
cout << n <<endl;
}
if(space!= 0)
sentence.erase(k,space);
cout << sentence <<endl;
}
}
len = sentence.length();
//cout << len <<endl;
} while (space != 0);
}
With this I was able to deal with capitalization issue but problem occurs when I try to check for more than one whitespace between two words. In the do loop I am somehow stuck in an infinite loop.
Like when I try and print the length of the string (len/len1) in the first line inside do-while loop, it keeps on running in an infinite loop. Similarly, when I try and print the value of k after the for loop, it again goes into infinite loop. I think it has to do with my use of do-while loop, but I am not able to get my head around it.
This is the output that I am receiving.
there are a few different issues with this code, but i believe that the code below addresses them. hopefully this code is readable enough that you can learn a few techniques. for example, no need to capitalize the first letter inside the loop, do it once and be done with it.
the usual problem with infinite loops is that the loop termination condition is never met--ensure that it will be met no matter what happens in the loop.
#include <iostream>
#include <string>
using namespace std;
int main() {
string sentence;
cout << "Enter the sentence: ";
getline(cin, sentence);
int len = sentence.find(".", 0) + 1; // up to and including the period
// Dealing with capitalizations
if (islower(sentence[0]))
sentence[0] = toupper(sentence[0]);
for (int j = 1; j < len; j++)
if(isupper(sentence[j]))
sentence[j] = tolower(sentence[j]);
// eliminate duplicate whitespace
for (int i = 0; i < len; i++)
if (isspace(sentence[i]))
// check length first, i + 1 as index could overflow buffer
while (i < len && isspace(sentence[i + 1])) {
sentence.erase(i + 1, 1);
len--; // ensure sentence decreases in length
}
cout << sentence.substr(0, len) << endl;
}
Here goes
std::string sentence;
std::string new_sentence;
std::cout << "Enter the sentence: ";
std::getline(std::cin, sentence);
bool do_write = false; // Looking for first non-space character
bool first_char = true;
// Loop to end of string or .
for (unsiged int i = 0; i < sentence.length() && sentence[i] != '.'; ++i) {
if (sentence[i] != ' ') { // Not space - good - write it
do_write = true;
}
if (do_write) {
new_sentence += (first_char ? toupper(sentence[i]) : tolower(sentence[i]);
first_char = false;
}
if (sentence[i] == ' ') {
do_write = false; // No more spaces please
}
}
if (i < sentence.length()) { // Add dot if required
new_sentence += '.';
}
I am rather new to c++ and I am taking my first course on it. I need to make a program that accepts input from the user like so "HelloHowAreYouToday" and at each capital letter turn it into a lower case letter and split apart the c string to look like this "Hello how are you today". Here is my code so far.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;
int main()
{
char sentence[100];
int size;
cout << "Enter a sentence with no spaces, make first letter in each word an upper case: ";
cin.getline(sentence, 100);
size = strlen(sentence);
char * manipSent = new char[size + 1];
for (int i = 1; i < size + 1; i++)
{
if (sentence[i] >= 'A' && sentence[i] <= 'Z')
{
manipSent[i] = ' ';
manipSent[i] = tolower(sentence[i]);
}
else;
manipSent[i] = tolower(sentence[i]);
}
manipSent[0] = sentence[0];
manipSent[size] = NULL;
cout << endl;
cout << "Original Sentence: " << sentence << endl;
cout << endl;
cout << "Altered Sentence: " << manipSent << endl;
delete[] manipSent;
return 0;
}
The issue I am having is splitting the words up, the out put looks like "Hellohowareyoutoday" but when I try to add a space in between the words the first letter in each word gets erased. Any input would be appreciated.
This is because whenever you put a space in your string, you immediately overwrite it by the lowercase version of the letter. If you write multiple values to one space, only the last value remains. This is why you don't have any spaces in your resulting string.
manipSent[i] = ' '; /* manipSent is now a space */
manipSent[i] = tolower(sentence[i]); /* overwrite manipSent[i] */
In order to do what you are trying to do, you need another variable besides i to keep track of where you are writing into manipSent. Look at the code below - I've created a new variable j that keeps up with i when you're copying characters, but if you add a space, it gets incremented again to deal with the fact that the new string is going to be larger than the old one.
for (int i = 1, j = 1; i < size + 1; i++, j++)
{
if (sentence[i] >= 'A' && sentence[i] <= 'Z')
{
manipSent[j] = ' ';
j++;
manipSent[j] = tolower(sentence[i]);
}
else;
manipSent[j] = tolower(sentence[i]);
}
It is important to remember that manipSent will be longer than sentence - in fact, it will be up to twice as long, so make sure you make manipSent bigger before you try adding spaces to it.
I have a sentence, I want split the sentence so that adds each word in an array item.
I have done the following code but it still wrong.
string str = "Welcome to the computer world.";
string strWords[5];
short counter = 0;
for(short i=0;i<str.length();i++){
strWords[counter] = str[i];
if(str[i] == ' '){
counter++;
}
}
I'm answering since you should learn from your mistakes: just use the += string operator and your code will work:
// strWords[counter] = str[i]; <- change this
strWords[counter] += str[i]; <- to this
to remove the spaces (if you don't want to append them) just change the order of the space check, something like:
for (short i = 0; i<str.length(); i++){
if (str[i] == ' ')
counter++;
else
strWords[counter] += str[i];
}
anyway I'm suggesting to use the duplicate link Split a string in C++? too
Very ugly way to do it, #Cyber has linked to the best answer. But here's your "corrected" version:
string str = "Welcome to the computer world.";
string strWords[5];
short counter = 0;
for(short i=0;i<str.length();i++){
if(str[i] == ' '){
counter++;
i++;
}
strWords[counter] += str[i];
}
As mentioned in the comments, there are a lot of more convenient ways to split a string (strtok, std functionality, etc.), but if we talk about your sample, you should not assign the 'str[i]' but append it, since it is a single character that you want to append to the current word like this:
string str = "Welcome to the computer world.";
string strWords[5];
short counter = 0;
for(short i=0;i<str.length();i++){
if(str[i] == ' ' && !strWords[counter].empty()){
counter++;
}
else {
strWords[counter] += str[i];
}
}
But this will work only on the given input data, since you can access the array strWords outside bounds if you have more than five words. Consider using a following code:
string str = "Welcome to the computer world.";
vector<string> strWords;
string currentWord;
for(short i=0;i<str.length();i++){
if(str[i] == ' ' && !currentWord.empty()){
strWords.push_back(currentWord);
currentWord.clear();
}
else {
currentWord += str[i];
}
}
UPDATE
Since I assume you are new to C++, here is the demonstration of the space issue you have (if you only use the addition operator):
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
string str = "Welcome to the computer world.";
string strWords[5];
short counter = 0;
for(short i=0;i<str.length();i++){
strWords[counter] += str[i]; // Append fixed
if(str[i] == ' '){
counter++;
}
}
for(short i=0;i<5;i++){
cout << strWords[i] << "(" << strWords[i].size() << ")" << endl;
}
return 0;
}
Result: