0

I'm wondering why it prints so many spaces when I only ask it to print one. Here's the code:

#include <iostream>
#include <string>
using namespace std;
string ar[21] = "                    ";
int main()
     {
     ar[3] = "M";
     ar[4] = "n";
 
     for(unsigned int i=0 ; i<20 ; i++)
          {
          cout << ar[i] << ", ";
          }
 
     system("PAUSE");
     }
3
Contributors
5
Replies
6
Views
10 Years
Discussion Span
Last Post by ~s.o.s~
0

You are creating an array of strings in which each 'cell' would contain a string and initializing those strings to contain 20 characters. (approx). You either need to do

string ar[21] = " ";
//OR
string ar = "                    ";

And btw, you loop is off by one. You need to loop from 0 to 20 and not 0 to 19.

0

Well yes, a better way, rather than to count how many characters are in your string is to call the .length() function.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.