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");
     }

Recommended Answers

All 5 Replies

Member Avatar for iamthwee

Er, you're confusing strings with char arrays me thinks.

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.

Member Avatar for iamthwee

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

Thanks people, I'm learning here.

> Thanks people, I'm learning here.
Heh, welcome.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.