Using 'While' Instead of Range-For

Hello, I'm working through C++ Primer 5th, and in the exercise it asks me to write a program that uses a 'while' to change all the characters in a string to 'X'. I got the 'Range for' version to work correctly but having trouble with the 'while' version. Below is my code. Thanks for your help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "stdafx.h"
#include <iostream>
#include <string>
using std::cin; using std::getline; using std::cout; using std::endl;
using std::string;

int _tmain(int argc, _TCHAR* argv[])
{
	string s("some string");

	cout << s << endl; // cout prints correctly here

	while (!s.empty())
	{
		s = 'X'; // this puts X in s each time so there is always only one X in s
				//** this is also an endless loop 
	}

	cout << s << endl;
	
			
	return 0;
}
  
http://www.cplusplus.com/reference/string/string/empty/

Returns whether the string is empty (i.e. whether its length is 0)


You are not changing the length of the string at all, so i'm not sure why you're using this.
I guess you need to iterate over the string and use
http://www.cplusplus.com/reference/string/string/size/
in your while test condition.
Ah, that is my problem. Thanks for pointing that out. I missed it.
Topic archived. No new replies allowed.