Loops converting underscores back to spaces

The assignment is to create a program to ask for a college name, and use underscores in place of the spaces. We must use a loop to convert underscores back to spaces and display the converted string, This is all i have been able to come up with: Can you help me get a start on how the loop to convert back to spaces works?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <cstdlib>
#include <iostream>
using namespace std;

int main()
{
    string collegeName = "";
    cout << "Please enter college names with spaces replaced by underscores: ";
    cin >> collegeName;
    cout << "College: " << collegeName << endl;

	system("pause"); 
	return 0;
}
You could start at the beginning of the college name, check each character to see if it is an underscore, then take action based upon that.
im not quite sure i know what you mean, can you provide an example?
closed account (SECMoG1T)
To start with , try understand how to access individual characters in a string variable, After you are good
you can move on and think on how you could change those characters.

To access individual characters in a string we can use the subscript operator [] we can also use the library function at () e.g. collegename.at (0);//or any other index , you could also use iterators to do the same thing.

We can use a loop to iterate through the string and determine the content at each index, in your case you could use an "if" statement to check if the current index holds an underscore character, if so you could Change the character by assigning a blank char to the index, collegename [index]=' ';

You could also use the functions provided by the string library, below I made a function that uses library tools to get the job done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
 #include <string>
 #include <iostream>
 
 using namespace std;

 string conv_uscore (string collegename)
  {
     string::size_type index=0;
     while ((index=collegename.find ('_'))!=string::npos)
        {
             collegename [index]=' ';
              ++index; 
        }
    
         return collegename;
   }



   int main ()
  {
    string name ("___smart__college_");
    cout <<conv_uscore (name);
  }


output:
   smart  college 


Some reference will also help you understand std::strings better.
http://www.tutorialspoint.com/cplusplus/cpp_strings.htm
http://www.cplusplus.com/reference/string/string/
Last edited on
Topic archived. No new replies allowed.