locked
String Lenght (Even or Odd) RRS feed

  • Question

  • Hello,

    I'm trying to make a small appilcation but I'm having problem getting the program to know if a string that the user entered was EVEN or ODD.

    #include <iostream>
    #include <string>
    
    // say what standard-library names we use
    using std::cin;         using std::endl;
    using std::cout;        using std::string;
    
    
    int main()
    {
    	// ask for the person's name
    	cout << "Please enter your first name: ";
    
    	// read the name
    	string name;
    	cin >> name;
    	// build the message that we intend to write
    	if (name.size % 2 == 0)
    		{
    		const string greeting = "Hello, " + name + "!";
    	else
    		const string greeting = "Hello, " + name + "! ";
    		}
    My problem lies here as I'm trying to figure out how to tell the program to check if the string entered had a even or odd number of characters.

    Example would be: Frank

    Whereas Frank = 5 Character = Odd Number of character I want to add a condition where if string name is odd I can change the string greeting.

    // build the message that we intend to write
    if (name.size % 2 == 0)
    {
    const string greeting = "Hello, " + name + "!";
    else
    const string greeting = "Hello, " + name + "! ";
    }
    I tryed a few things but I'm not sure about those modulo and if or not there is a better way to determine if a string entered by a user is even or odd in lenght.

    THank you in advance for any information that could help me solve this problem!
    Thursday, August 20, 2009 8:45 AM

Answers

  • Thank you both for your kind reply, I actually managed to keep the const string while adding a condition and it compiled nicely! : )

    Here is the code I managed to come up with, I cleared this excersise with this since I needed to keep the const string greeting!

    /*Original Version of this program 
      can be found in the Accelerated 
      C++ Books Chapter 2
    
     *********************************
     * Modified Version of Frame.cpp *
     * Programmer: Seishin Kan       *
     * Last Modifed August 20, 2009  *
     *********************************/
    
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    
    	{
    	//get the person's first name
    	cout << "Enter your first name? ";
    
    	//read the name
    	string name;
    	cin >> name;
    
    	//build the message that we intend to write
            //ORIGINAL CODE
    	//const string greeting = "Hello, " + name + "!";
    	
    	/***********************************************
    	 *Modified by Seishin Kan on August 20, 2009   *
    	 *Added a condition where if the string entered* 
    	 *is even a space will be added at the end of  * 
    	 *the const string greeting		       *
    	 ***********************************************/
    	const string greeting = name.length() % 2 == 0 ? "Hello, " + name + "! " :
    							 "Hello, " + name + "!";	
    
    	// the number of blanks surrounding the greeting
    	const int pad = 1;
    
    	// the number of rows and columns to write
    	const int rows = pad * 2 + 3;
    	const string::size_type cols = greeting.size() + pad * 2 + 2;
    
    	// write a blank line to separate the output from the input
    	cout << endl;
    
    	// write `rows' rows of output
    	// invariant: we have written `r' rows so far
    	for (int r = 0; r != rows; ++r) {
    
    		string::size_type c = 0;
    
    		// invariant: we have written `c' characters so far in the current row
    		while (c != cols) {
    
    			// is it time to write the greeting?
    			if (r == pad + 1 && c == pad + 1) {
    				cout << greeting;
    				c += greeting.size();
    			} else {
    
    				// are we on the border?
    				if (r == 0 || r == rows - 1 ||
    				    c == 0 || c == cols - 1)
    					cout << "*";
    				else
    					cout << " ";
    				++c;
    			}
    		}
    
    		cout << endl;
    	}
    
    	return 0;
    }
    
    

    Thanks everyone for the help it was very much appreciated!




    • Edited by Seishin Kan Friday, August 21, 2009 12:49 AM why does this board reformat code by itself?
    • Marked as answer by Seishin Kan Friday, August 21, 2009 12:50 AM
    Friday, August 21, 2009 12:48 AM

All replies

  • #include <iostream>
    #include <string>
    
    using namespace std;
    
    void main()
    {
    
    string szName;
    
    cout<<"Enter name ";
    cin>>szName;
    
    if( szName.Length() %2 ==0)
        cout<<"String length is even"<<endl;
    else
        cout<<"String length is odd"<<endl;
    
    }
    How did you even get to compile your code? I mean - there's an else condition (with no mathcing if, inside the control block of the only if condition). Among other things, it cannot be name.size, it should have been name.size(), etc.,
    Best regards, Rajesh R Subramanian.
    Thursday, August 20, 2009 8:58 AM
  • ah yes I did make some type while typing the code here but anyway I rewrote the whole code now but I'm still left with the same problem. Thanks for the help but I'm trying to pass the result into a statement and declare a const string using a IF/ELSE. But I'm not sure how this work.

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
    	// ask for the person's name
    	cout << "Please enter your first name: ";
    
    	// read the name
    	string name;
    	cin >> name;
    	// build the message that we intend to write
    		if (name.length() % 2 == 0)
                            {
    const string greeting = "Hello, " + name + "!"; }
    else {
    const string greeting = "Hello, " + name + " !" }
    I've come up with this but than the string greeting become unidentified.

    Below is the rest of the program so far.

    // the number of blanks surrounding the greeting
    	const int pad = 2;
    
    	// the number of rows and columns to write
    	const int rows = pad * 2 + 4;
    	const string::size_type cols = greeting.size() + pad * 2 + 4;
    
    	// write a blank line to separate the output from the input
    	cout << endl;
    
    	// write `rows' rows of output
    	// invariant: we have written `r' rows so far
    	for (int r = 0; r != rows; ++r) {
    
    		string::size_type c = 0;
    
    		// invariant: we have written `c' characters so far in the current row
    		while (c != cols) {
    
    			// is it time to write the greeting?
    			if (r == pad + 1 && c == pad + 1) {
    				cout << greeting;
    				c += greeting.size();
    			} else {
    
    				// are we on the border?
    				if (r == 0 || r == rows - 1 ||
    				    c == 0 || c == cols - 1)
    					cout << "*";
    				else
    					cout << " ";
    				++c;
    			}
    		}
    
    		cout << endl;
    	}
    
    	return 0;
    }
    I'm not too sure what I need to do, I'm reading more about IF and ELSE to see if I can declare a String while using them.



    Thursday, August 20, 2009 9:35 AM
  • Quote>I did make some type while typing the code here

    Never retype code to enter it into a posting. You waste your time and that of everyone else
    who tries to help. Invariably when you do that either new errors will be introduced or the
    original problem will be altered, etc. Learn how to use the Windows clipboard to do copy
    and paste operations so that the code you post in a message exactly matches what you have
    in your source code.

    - Wayne
    Thursday, August 20, 2009 9:46 AM
  • Your greeting strings are local to the if...else blocks. Eithet take the declaration of greeting out of the if...else or use ternary expression. But I do not see any difference between your two versions of greeting .

    Also you cannot use string::operator +() with a string literal on the left. You must do

    const string greeting = std::string("Hello, ") + name + "!" ;

    Your code must have had compile errors. Either fix your code before posting, or ask specific question about the compiler error if you do not understand it.

    David Wilkinson | Visual C++ MVP
    Thursday, August 20, 2009 11:31 AM
  • wow, such harsh comments.

    I did copy the code from the source files, it's not like I retyped the code here for my own amusement, I simply copy/pasted the code here. (since I'm a beginner in C++ there was some typo there and there, which I'm deeply sorry for)

    By the way the main idea of this program and most of the code come from Accelerated C++ Books (http://www.acceleratedcpp.com/), Chapter Two: form.cpp and here is the main Source Code (without any changes from my part)

    #include <iostream>
    #include <string>
    
    // say what standard-library names we use
    using std::cin;         using std::endl;
    using std::cout;        using std::string;
    
    
    int main()
    {
    	// ask for the person's name
    	cout << "Please enter your first name: ";
    
    	// read the name
    	string name;
    	cin >> name;
    
    	// build the message that we intend to write
    	const string greeting = "Hello, " + name + "!";
    
    	// the number of blanks surrounding the greeting
    	const int pad = 1;
    
    	// the number of rows and columns to write
    	const int rows = pad * 2 + 3;
    	const string::size_type cols = greeting.size() + pad * 2 + 2;
    
    	// write a blank line to separate the output from the input
    	cout << endl;
    
    	// write `rows' rows of output
    	// invariant: we have written `r' rows so far
    	for (int r = 0; r != rows; ++r) {
    
    		string::size_type c = 0;
    
    		// invariant: we have written `c' characters so far in the current row
    		while (c != cols) {
    
    			// is it time to write the greeting?
    			if (r == pad + 1 && c == pad + 1) {
    				cout << greeting;
    				c += greeting.size();
    			} else {
    
    				// are we on the border?
    				if (r == 0 || r == rows - 1 ||
    				    c == 0 || c == cols - 1)
    					cout << "*";
    				else
    					cout << " ";
    				++c;
    			}
    		}
    
    		cout << endl;
    	}
    
    	return 0;
    }
    
    


    It compile nicely, but they ask to do some excersises on my own which is what I'm trying to accomplish here.

    What I'm basicly trying to figure out is and I will say it in the most basics of ways possible without using C++ codes since it's clearly not working for me to ask in this manner for the moment...

    The above program first ask the user to enter is first name:

    cout << "Please enter your first name: ";
    

    What I'm trying to figure out is a way for me to verify if the entered string (name) is EVEN or ODD in LENGTH.

    ------------------------
    Example:

    Dan   = 3 Letter = Odd
    Erik   = 4 Letter = Even

    ------------------------

    The reason behind this is that I want to add a SPACE after the sentence if the STRING is EVEN.

    As follow:

    ------------------------
    IF STRING NAME = ODD in LENGTH the following would be written for the const string greeting
    const string greeting = "Hello, " + name + "!";
    BUT IF STRING NAME = EVEN in LENGTH the following would be written for the const string greeting (yeah it's a SPACE added after the asterix like this "! " instead of "!" this at the end of the string.

    const string greeting = "Hello, " + name + "! ";

    Of course if I could manipulate the string name directly that would work, also like if I could tell some conditions for the string name before doing the cin >> name; that would work too or even make a check after the person enter the string itself would be even better maybe if at all possible.

    	// ask for the person's name
    cout << "Please enter your first name: ";

    // read the name
    string name;
    cin >> name;

    The easiest way would be if I could check the length before doing the cin >> name; or string name;

    I'm sorry if my question seemed a bit out of places, but I'm trying my best to figure this out, I went ahead and read everything about operator concerning string at http://www.cplusplus.com/reference/string/string/

    Two Iterators : length and size both return length of string

    And then there is the Modifiers : insert that would look like it could do what I want but I seems to lack the knowledge to get this done...

    Also here is what I based my ODD and EVEN:
    (the following code was taken from: http://www.cplusplus.com/doc/tutorial/functions2/)

    // declaring functions prototypes
    #include <iostream>
    using namespace std;
    
    void odd (int a);
    void even (int a);
    
    int main ()
    {
      int i;
      do {
        cout << "Type a number (0 to exit): ";
        cin >> i;
        odd (i);
      } while (i!=0);
      return 0;
    }
    
    void odd (int a)
    {
      if ((a%2)!=0) cout << "Number is odd.\n";
      else even (a);
    }
    
    void even (int a)
    {
      if ((a%2)==0) cout << "Number is even.\n";
      else odd (a);
    }
    


    Thanks in advance for any help and I'm sorry if I made mistakes in my first post, I hadn't paid attention so I will try to recheck more carefully from now on.






    Thursday, August 20, 2009 7:05 PM
  • We are not being harsh, just trying to help you. If you post code that does not compile it is not possible to say why it does not work, because it is not possible to run it and find out what it currently does.

    But actually you are posting complete (small) programs, which is very good, because a responder can actually cut and paste the code into Visual Studio.

    Yes, my mistake

    const string greeting = "Hello, " + name + "!";

    is ok. You can't do this with CString, but it seems you can for std::string. One learns something every day.

    As to your question, I don't really see what the problem is.

    I guess  I would do

    string greeting = "Hello, " + name + "!";
    if (name.size()%2 == 0)
    {
      greeting += ' ';
    }

    If you insist on making greeting const, you can initialize it using the ternary operator as I suggested before.

    By the way, length() and size() are not iterators. But yes, they do the same thing. The existence of both is for historical reasons.



    David Wilkinson | Visual C++ MVP
    • Edited by davewilk Thursday, August 20, 2009 8:41 PM (formatting/typo)
    Thursday, August 20, 2009 8:40 PM
  • Quote>The easiest way would be if I could check the length before doing the cin >> name;

    Think about that awhile. The string (name) doesn't exist until the user types it in.
    As it's typed in the cin extraction operator retrieves the characters until it encounters
    whitespace or eof. Now, how do you suppose you could possibly check the length *before*
    the cin (i.e. - before it's typed in)?

    - Wayne

    Thursday, August 20, 2009 9:00 PM
  • Thank you both for your kind reply, I actually managed to keep the const string while adding a condition and it compiled nicely! : )

    Here is the code I managed to come up with, I cleared this excersise with this since I needed to keep the const string greeting!

    /*Original Version of this program 
      can be found in the Accelerated 
      C++ Books Chapter 2
    
     *********************************
     * Modified Version of Frame.cpp *
     * Programmer: Seishin Kan       *
     * Last Modifed August 20, 2009  *
     *********************************/
    
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    
    	{
    	//get the person's first name
    	cout << "Enter your first name? ";
    
    	//read the name
    	string name;
    	cin >> name;
    
    	//build the message that we intend to write
            //ORIGINAL CODE
    	//const string greeting = "Hello, " + name + "!";
    	
    	/***********************************************
    	 *Modified by Seishin Kan on August 20, 2009   *
    	 *Added a condition where if the string entered* 
    	 *is even a space will be added at the end of  * 
    	 *the const string greeting		       *
    	 ***********************************************/
    	const string greeting = name.length() % 2 == 0 ? "Hello, " + name + "! " :
    							 "Hello, " + name + "!";	
    
    	// the number of blanks surrounding the greeting
    	const int pad = 1;
    
    	// the number of rows and columns to write
    	const int rows = pad * 2 + 3;
    	const string::size_type cols = greeting.size() + pad * 2 + 2;
    
    	// write a blank line to separate the output from the input
    	cout << endl;
    
    	// write `rows' rows of output
    	// invariant: we have written `r' rows so far
    	for (int r = 0; r != rows; ++r) {
    
    		string::size_type c = 0;
    
    		// invariant: we have written `c' characters so far in the current row
    		while (c != cols) {
    
    			// is it time to write the greeting?
    			if (r == pad + 1 && c == pad + 1) {
    				cout << greeting;
    				c += greeting.size();
    			} else {
    
    				// are we on the border?
    				if (r == 0 || r == rows - 1 ||
    				    c == 0 || c == cols - 1)
    					cout << "*";
    				else
    					cout << " ";
    				++c;
    			}
    		}
    
    		cout << endl;
    	}
    
    	return 0;
    }
    
    

    Thanks everyone for the help it was very much appreciated!




    • Edited by Seishin Kan Friday, August 21, 2009 12:49 AM why does this board reformat code by itself?
    • Marked as answer by Seishin Kan Friday, August 21, 2009 12:50 AM
    Friday, August 21, 2009 12:48 AM