how do i write a program like this?

i am trying to write a program that asks for user's name after the user enters his name, the length of his name will be displayed.
1
2
3
4
5
char Name[20]
cin>>char Name;
int length
while(length<20)
{length++;cout<<name[length]<<endl;}
Why not use strings ?

1
2
3
string name; 
getline(cin, string);
cout << name.size() << endl;
You can use the string class. Save the user name in a string, and then call the length() function.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

using namespace std;

int main( int argc, char* argv[] ) {
    string str;
    
    cout << "Enter your name: ";
    getline( cin, str );

    cout << "The length of your name is " << str.length() << " characters.\n";
    
    cin.get();

    return 0;
}



Edit: Ninja'ed!! :)
Last edited on
i'll have to use character array and while loop, it's part of assignment.
Last edited on
closed account (zb0S216C)
When a string is given as input, the compiler will append a null-character ('\0') at the end of the string. When this character is encountered, you know that the string ends there. Because this character has the value of zero, it corresponds to the Boolean value of false. So far, you're on the right track, but you're not counting the string length properly. Here's how I would do it given your restrictions:

1
2
3
int iLength(0);
for(int iIndex(0); Name[iIndex]; ++iIndex)
    ++iLength;

This code is very simple. Let's walk through it:

First we declare "iLength", which we use to store the length of the string. Then, we begin a loop. The initialisation section of the loop introduces "iIndex", which represents the index of the character we're accessing. To understand why we have this, we must look into the condition section of the loop. The condition tests for a character, other than the null-character (remember what I said about it above?). If the null-character is encountered, the condition evaluates to false, and the loop ends. However, any other character is counted. So, if the "iIndexth" character in "name" is a null-character, the loop will stop. The increment section of the loop is straight forward; move to the next character.

Wazzak
Topic archived. No new replies allowed.