1

In this program,I store integer values from 0 to 4 in a string and I want to print this string.

CODE:

int main()
{
 string str=" ";
 for(int i=0;i<5;i++)
   str[i]=i+'0';
 cout<<str;
 return 0;
}

But when i run this program,it just shows first element(means '0') of string.

Can anybody tell me the reason,Why this program does not print whole string in output?

Amit Nandal
  • 118
  • 1
  • 6
  • 1
    FYI -- Better to stay away from magic numbers and simply do `str[i] = i + '0';` – PaulMcKenzie Dec 31 '19 at 14:25
  • 2
    Undefined behaviour, due to writing 5 characters to a string that contains a single character. Accessing `str[i]` with `i` out of bounds does not magically resize the string. – Peter Dec 31 '19 at 14:56
  • 1
    @Peter That's an _answer_. Not a comment. This is a Q&A. Not a chatroom. Many of your comments give solutions to the problem, an answer to the question. Please stop doing that. We have peer review in the answer section for a reason. Thank you. – Lightness Races in Orbit Dec 31 '19 at 15:47

5 Answers5

3

The code doesn't work as expected because you exceeded the string greatest index which is 0 because the size of your string is 1 as the previous answer say.

This is a modification

int main()
{
    std::string str="     ";
    for(int i=0;i<5;i++)
        str[i]=i+'0';
    std::cout<<str;

    return 0;
}
asmmo
  • 6,922
  • 1
  • 11
  • 25
3

Actually, when you are using for loop, it is accessing position in string changing it. Since when you have initialized string as string str = " " this means our string is of single whitespace. After which for loop access that string and look for the index str[i] and changes its value to i+'0'.

So, when we are writing code as

for(int i=0; i< 5; i++){
  str[i]=i+'0';
  cout<<str[i];
}

it seems, like for that block, str[i] value is i+'0', which is printed, but str doesn't update. Due to which when you do cout<<str; it again shows 0 as the answer.

To solve this issue we can use property of concatenation, refer the below code

 #include <iostream>
 using namespace std;

 int main()
 {
 string str;
 for(int i=0;i<5;i++)
    str+=i+'0';
 cout<<str;
 return 0;
 }

This gives the required result as 01234.

Hope this helps you.

2

You are exceeding array boundaries, because you initialized the string as containing only one space. If you give it more spaces, the code works:

string str = "     ";
SurvivalMachine
  • 7,946
  • 15
  • 57
  • 87
  • But when i am printing this string with the help of for loop,this program prints whole string.e.g:for(int i=0;i<5;i++){ cout< – Amit Nandal Dec 31 '19 at 14:25
  • 1
    @AmitNandal -- Did you make the changes suggested in the answer given to you? If not, then your code has undefined behavior due to accessing elements out-of-bounds. – PaulMcKenzie Dec 31 '19 at 14:37
  • Sir,but when i print this string with the help of for loop,it show correct output(01234). – Amit Nandal Dec 31 '19 at 14:39
  • 2
    @AmitNandal It still is undefined behavior. That you observe output that matches your expectation is a possible manifestation of undefined behavior. – j6t Dec 31 '19 at 15:02
1

when we are assigning

string str = " "; 

here " " is of type const char[2];size is 2: 1 lenght of character and 1 length for '\0' (Null Terminated) character. This gets copied into string str by calling operator= overloaded function.

When We are trying to access str[] with more than 0,1 index of subscript[] say 2 its doing memory violation and that is causing the exception "string subscript out of range",

if you try to access [0] and [1] it will work fine or instead of accessing particular location using array subscript, concatenation (+=) will help.

Pankaj
  • 401
  • 1
  • 6
  • 16
1
int main()
{
 string str=" ";        // str.size() == 1

 for(int i=0;i<5;i++)
   str[i]=i+'0';        // str.size() is still 1

 cout<<str;             // str.size() is still 1 
}

In str[i], if ...

  • i>str.size() you are accessing the array out of bounds and get undefined behaviour.

  • i==str.size() (where the null terminator is) and you change that value, you also get undefined behaviour.

But when i am printing this string with the help of for loop,this program prints whole string.e.g:

for(int i=0; i<5; i++) {
    cout<<str[i]<<" "; 
}

Why this loop print whole string, but not cout<<str?

You've made changes out of bounds and have undefined behaviour. It's possible that you can read the values back one-by-one (instead of getting a program crash) due to short string optimization - but the size() of str is still 1 since you haven't changed the size.

If your loop had gone further, outside the area used by short string optimization, like this:

for(int i=0; i<25; i++) {
    cout<<str[i]<<" "; 
}

it would be even more likely to result in a crash.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108