Jump to content

entering a string using for loop, "¶"

- - - - -

  • Please log in to reply
11 replies to this topic

#1
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
Hi

In the code below both blue cout statements should produce the same result because in both cases name[] variable is being worked on. But you see in one case I get this "¶". Why is so? Please let me know. Thanks.

When a string is entered using cin a space is considered to be end of a string. While entering the name using the for loop I inserted two spaces but they were ignored. Why is so?

Please help me. Thanks.


// read_your_name.cpp

// read and print your name using an array and using

// cin, for loop, cin.get()


#include <iostream>

#include <cstdlib>

#include <cstring>

#include <string>


using namespace std;


const int C = 20;


int main()

{

        int i;

        char name[C];

        string urname;


        cout << "enter your name: ";

        cin >> name;


        cout << "your name is: Mr. " << name << endl;



        cout << "enter your name: ";


        for (i=0; i<C; i++)

        {

                cin >> name[i];

        }


        cin.ignore();


        cout << "your name is: Mr. ";


        [COLOR="blue"]for (i=0; i<C; i++)

        {

                cout << name[i];

        }[/COLOR]


        cout << endl;


        [COLOR="blue"]cout << "your name is: Mr. " << name << endl;[/COLOR]



        cout << "\nenter your name: ";

        cin.get(name, C);


        cout << "enter your name: ";

        getline(cin, urname);


        cout << "your name is: Mr. " << name << endl;


        system("pause");

        return 0;

}


OUTPUT

enter your name: jackson

your name is: Mr. jackson

enter your name: j

a

c

k

s

o

n

   [COLOR="red"]//space[/COLOR]

h

e

i

g

h

t

s

  [COLOR="red"]//space[/COLOR]

0

0

0

0

0

0

your name is: Mr. jacksonheights000000

your name is: Mr. jacksonheights000000[COLOR="red"]¶[/COLOR]


enter your name: jackson heights

enter your name: your name is: Mr. jackson heights

Press any key to continue . . .


I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#2
NewProgrammer

NewProgrammer

    Newbie

  • Members
  • PipPip
  • 20 posts
The problem is "null character".Null character views the string's end.In your way, you don't create a null character.Null character is '\0'
Solution:

for (i=0; i<C; i++)

{

    cin >> name[i];

}

name[20] = '\0';

This code declarates a null character.In this way you can 19 characters of name.Because 20. character is null character.

#3
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts

NewProgrammer said:

The problem is "null character".Null character views the string's end.In your way, you don't create a null character.Null character is '\0'
Solution:

for (i=0; i<C; i++)

{

    cin >> name[i];

}

name[20] = '\0';

This code declarates a null character.In this way you can 19 characters of name.Because 20. character is null character.

Hi NP

Isn't there a slight error? Please forgive me if I'm wrong.

0...19 counts to 20 elements.

I think it should be
for(i=0; i<(C-1); i++)
. What do you say?

The looping would go from 0 to 18 which sums up to 19 elements.


// C = 20;

for (i=0; [color="red"]i<C;[/color] i++)

{

    cin >> name[i];

}

name[20] = '\0';


I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#4
NewProgrammer

NewProgrammer

    Newbie

  • Members
  • PipPip
  • 20 posts
Yes.You are right.
But Visual Studio didn't warn. :(

#5
jakash3

jakash3

    Newbie

  • Members
  • PipPip
  • 21 posts
There's 21 characters (1 reserved for null) but index counting starts at 0.
char name[21];
...
for (i = 0; i < 20; i++)
...
name[20] = 0;

Posted Image
Posted Image

#6
NewProgrammer

NewProgrammer

    Newbie

  • Members
  • PipPip
  • 20 posts
jakash;
It is true.I busted :D

#7
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts

NewProgrammer said:

jakash;
It is true.I busted :D

Does this mean I'm correct?! :)
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#8
NewProgrammer

NewProgrammer

    Newbie

  • Members
  • PipPip
  • 20 posts
Yeah :)
But Visual Studio didn't warn :(
:)

#9
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
Thanks for the confirmation.
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#10
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
Hi :)

Is the comment in blue correct? Please let me know. Thanks.


// strcopy1.cpp

// copies a string using a for loop


#include <iostream>

#include <cstdlib>

#include <cstring>


using namespace std;


int main()

{

        char str1[] = "Oh, Captain, my Captain! "

                      "our fearful trip is done";


        const int MAX = 80;

        char str2[MAX];


        int i;


        for(i=0; i<strlen(str1); i++)

        {

            str2[i] = str1[i];

        }


        /*

        [COLOR="blue"]Although Null terminator would be inserted automatically

        but only after 79 elements have been entered.


        If str1 was 20 elements long, then (79 - 20) elements would

        contain garbage values. Therefore, one has to enter NULL

        explicitly.[/COLOR]

        */


        str2[i] = '\0';


        cout << str2 << endl;


        system("pause");

        return 0;

}


I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#11
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
If you initialize str2 to zero, and accept sizeof str2 characters then there will be always a terminator at the end of your char array.

However if it is not initialized, you must do as you were with your "i" variable after the loop and record how many characters were written, and then of course write the terminator afterwards.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#12
fayyazlodhi

fayyazlodhi

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 403 posts
Hi jackson,

I guess a few things left unanswered and you should be clear about them.

when you type something like


for (int i=0; i< n; i++) // n is some upper limit number

cin >> arr[i]; // arr is a char array whose size should at least be n+1

You are reading one character at a time into the array. So there will never by any automatic copy of null.

It is only automatically inserted when you do things like

char arr[10];

cin >> arr; // Note that we are not reading char by char, but rather the whole string


// OR

strcpy(arr, arr2)  // etc.


Your first initial output contained garbage character because your loop was running from 0 - upper limit, irrespective of string terminated earlier i.e. even if a '\0' is found your loop would still continue unless you tell it to stop printing.

Correct way to do that will be


for (i=0; i<C && name[i] !='\0'; i++) // either it goes upto one less than C OR if it finds a null char

        {

                cout << name[i];

        }


Lastly, Visual studio would never warn against buffer over flow since character arrays in c are not checked for ranges. Use STL vector instead. It is not a compiler limitation but rather a C language behavior.

Edit: Adding one more point

If you see

for (int i=0; i<strlen(arr); i++)  {..}


It will not copy the terminating null of arr. The reason is that internally string length runs a loop and keeps incrementing a counter until a null is found, upon which it breaks the loop and returns the counter. So the length returned by strlen always excludes the null character and therefore if needed you will have to copy null manually in the destination array.

Edited by fayyazlodhi, 22 June 2011 - 02:17 PM.
Adding one forgotten case

Today is the first day of the rest of my life




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users